Files
syops/backend/tests/test_shipping_notice_intakes_lifecycle.py
T
hugo 5ef8329bd8 refactor(shipping-notice): 重构货代发货通知状态管理,移除废弃的process_status字段
统一货代发货通知的业务阶段为四个标准阶段:接收解析、订单复核、发货准备、上传完成
设置 ui_state 为前端唯一状态数据源,不再依赖 process_status 驱动业务流程
删除 shipping_notices 表的废弃 process_status 列及对应复合索引,新增数据库迁移脚本
替换全栈代码中所有对 process_status 的引用为生命周期、上传状态等领域字段
更新相关文档、测试用例与前端展示逻辑适配新的状态管理规则
2026-08-15 10:19:10 +08:00

1075 lines
43 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
tests/test_shipping_notice_intakes_lifecycle.py
用途:验证 Intake 创建/取消/重试、候选审核 API 与状态投影生命周期。
依赖:pytest、conftest app fixture、MinIO mock、test_shipping_notice_intake_helpers。
逻辑:由原 test_shipping_notice_intakes.py 按域拆分;建批路径已删除。
"""
from __future__ import annotations
import threading
import time
from datetime import datetime
from unittest.mock import patch
import pytest
from werkzeug.datastructures import FileStorage
from io import BytesIO
from app import db
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
from app.models import (
FileAsset,
ShippingDocumentLayoutVersion,
ShippingOrderCandidate,
ShippingOrderDocument,
ShippingOrderIntake,
ShippingOrderExtraction,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
ShippingNotice,
User,
)
from app.services.file_assets.service import upload_file_asset
from app.services.shipping_notice.intake_service import create_shipping_notice_intake
from app.services.shipping_notice.business_fingerprint import (
build_business_fingerprint,
build_content_fingerprint,
)
from tests.test_shipping_notice_intake_helpers import (
_make_upload,
_minimal_pdf_bytes,
_seed_parsed_intake,
)
pytest_plugins = ['tests.test_shipping_notice_intake_helpers']
def test_intake_status_exposes_layout_lifecycle_without_blocking_terminal_fallback(app, shipping_user):
"""
Intake 状态须区分附件预解析与版面任务;只有 queued/running 阻断发送。
关键断言:无任务为 not_required;活动任务为 processing;ready/failed 等终态统一为 completed,
使前端继续轮询活动任务但保留文本/Dify 兜底能力。
"""
from app.services.shipping_notice.intake_service import serialize_intake
with app.app_context():
asset = FileAsset(
asset_no='FA-LAYOUT-STATUS-001', owner_user_id=shipping_user.id,
original_filename='layout-status.eml', storage_provider='minio',
storage_bucket='hxops-file-assets', storage_key='temporary/layout-status.eml',
content_hash='a' * 64, file_size=100, mime_type='message/rfc822',
upload_status='ready', lifecycle_status='temporary',
)
db.session.add(asset)
db.session.flush()
intake = ShippingOrderIntake(
intake_no='SNI-LAYOUT-STATUS-001', asset_id=asset.id, user_id=shipping_user.id,
purpose='shipping_notice', parse_status='parsed', parser_version='v6',
)
db.session.add(intake)
db.session.flush()
document = ShippingOrderDocument(
intake_id=intake.id, document_type='attachment', attachment_key='order.pdf',
filename='order.pdf', classification='order_notice', parse_status='parsed',
content_hash='b' * 64,
)
db.session.add(document)
db.session.flush()
# 没有独立版面任务时不阻断普通文本附件。
assert serialize_intake(intake, asset=asset)['layout_status'] == 'not_required'
version = ShippingDocumentLayoutVersion(
document_id=document.id, version=1, status='queued', source_content_hash='b' * 64,
parser_key='mineru:test', parser_name='mineru', contract_version='shipping_document_layout.v1',
issues_json=[],
)
db.session.add(version)
db.session.flush()
processing = serialize_intake(intake, asset=asset)
assert processing['layout_status'] == 'processing'
assert processing['layout_summary']['queued'] == 1
# 失败也是终态;订单抽取可以继续使用文本或 Dify 兜底。
version.status = 'failed'
version.finished_at = datetime.utcnow()
db.session.flush()
completed = serialize_intake(intake, asset=asset)
assert completed['layout_status'] == 'completed'
assert completed['layout_summary']['failed'] == 1
def test_candidate_review_duplicate_api_and_access_guards(app, client):
"""Candidate API 应支持修订、刷新和决策,并阻止越权或已消费候选修改。"""
from app.core.auth.jwt import issue_local_access_token
with app.app_context():
owner = User(username='candidate-owner', email='candidate-owner@example.com', password_hash='x')
other = User(username='candidate-other', email='candidate-other@example.com', password_hash='x')
db.session.add_all([owner, other])
db.session.flush()
asset = FileAsset(
asset_no='FA-CANDIDATE-API-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}/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(asset)
db.session.flush()
intake = ShippingOrderIntake(
intake_no='SNI-CANDIDATE-API-001',
asset_id=asset.id,
user_id=owner.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='attachment-1',
filename='order-7001.pdf',
content_hash=asset.content_hash,
classification='order_notice',
parse_status='parsed',
)
existing = ShippingNotice(
task_no='SN-CANDIDATE-EXISTING-001',
user_id=owner.id,
source_content_hash=asset.content_hash,
)
db.session.add_all([document, existing])
db.session.flush()
candidate = ShippingOrderCandidate(
candidate_no='SNC-CANDIDATE-API-001',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='test:SNC-CANDIDATE-API-001',
po_number='7001',
structured_result_json={
'business_summary': {
'po_number': '7001',
'lines': [{'reservation_id': '1000140351', 'part_number': 'SKU-1', 'qty': 1}],
},
},
validation_status='needs_review',
conflicts_json=[{'field': 'qty'}],
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()
owner_headers = {'Authorization': f'Bearer {issue_local_access_token(owner)}'}
other_headers = {'Authorization': f'Bearer {issue_local_access_token(other)}'}
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}],
},
},
headers=owner_headers,
)
assert patch_response.status_code == 200
patched = patch_response.get_json()['data']
assert patched['selected'] is False
assert patched['validation_status'] == 'ready'
# 模拟重复任务在审核完成前被关闭,采纳必须重新通过实时重复门禁。
with app.app_context():
existing = ShippingNotice.query.filter_by(task_no='SN-CANDIDATE-EXISTING-001').one()
db.session.delete(existing)
db.session.commit()
promote_response = client.post(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001/promote',
headers=owner_headers,
)
assert promote_response.status_code == 200
promoted = promote_response.get_json()['data']
assert promoted['candidate_status'] == 'accepted'
assert promoted['acceptance_mode'] == 'manual'
assert promoted['selected'] is True
repeated = client.post(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001/promote',
headers=owner_headers,
)
assert repeated.status_code == 200
assert repeated.get_json()['data']['candidate_status'] == 'accepted'
assert patched['conflicts'] == []
assert patched['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',
))
db.session.commit()
forbidden = client.patch(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001',
json={'selected': True},
headers=other_headers,
)
assert forbidden.status_code == 404
refresh = client.post(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001/duplicate-refresh',
headers=owner_headers,
)
assert refresh.status_code == 200
refreshed = refresh.get_json()['data']
assert refreshed['duplicate']['status'] == 'exact_file'
assert 'open_existing' in refreshed['duplicate']['allowed_actions']
resolution = client.post(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001/duplicate-resolution',
json={'action': 'open_existing', 'target_task_no': 'SN-CANDIDATE-EXISTING-001'},
headers=owner_headers,
)
assert resolution.status_code == 200
assert resolution.get_json()['data']['duplicate_resolution']['action'] == 'open_existing'
with app.app_context():
row = db.session.query(ShippingOrderCandidate).filter_by(
candidate_no='SNC-CANDIDATE-API-001',
).one()
row.consumed_task_id = db.session.query(ShippingNotice).filter_by(
task_no='SN-CANDIDATE-EXISTING-001',
).one().id
db.session.commit()
consumed = client.patch(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001',
json={'selected': True},
headers=owner_headers,
)
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():
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=[],
)
with pytest.raises(ConflictError) as provisional:
ensure_candidate_fulfillment_ready(candidate)
assert provisional.value.code == 'SHIPPING_NOTICE.CANDIDATE_ACCEPTANCE_REQUIRED'
candidate.candidate_status = 'accepted'
ensure_candidate_fulfillment_ready(candidate)
def test_upload_file_asset_creates_ready_record(app, shipping_user):
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
result = upload_file_asset(user_id=shipping_user.id, upload=_make_upload())
asset = db.session.query(FileAsset).filter_by(asset_no=result['asset_no']).one()
assert asset.upload_status == 'ready'
assert asset.lifecycle_status == 'temporary'
assert asset.content_hash
assert 'storage_key' not in result
def test_create_intake_queues_parse_job(app, shipping_user):
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset = upload_file_asset(user_id=shipping_user.id, upload=_make_upload())
with patch('app.services.shipping_notice.intake_service.enqueue', return_value=101) as enqueue_mock:
intake_data = create_shipping_notice_intake(
user_id=shipping_user.id,
asset_no=asset['asset_no'],
conversation_id='conv-intake-1',
)
assert intake_data['parse_status'] == 'queued'
enqueue_mock.assert_called_once()
assert enqueue_mock.call_args.kwargs.get('commit') is False
intake = db.session.query(ShippingOrderIntake).filter_by(intake_no=intake_data['intake_no']).one()
assert intake.parse_job_id == 101
def test_create_intake_integrity_race_returns_existing(app, shipping_user, monkeypatch):
"""并发首次插入撞唯一约束时须回落已有 Intake,不得 500。"""
with app.app_context():
from sqlalchemy.exc import IntegrityError
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(user_id=shipping_user.id, upload=_make_upload(b'race-intake'))
asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
winner = ShippingOrderIntake(
intake_no='SNI-RACE-WIN',
asset_id=asset.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='queued',
parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
parse_job_id=555,
)
db.session.add(winner)
db.session.commit()
calls = {'n': 0}
def _lock_side_effect(*, asset_id, purpose, parser_version):
calls['n'] += 1
if calls['n'] == 1:
return None
return (
db.session.query(ShippingOrderIntake)
.filter_by(intake_no='SNI-RACE-WIN')
.execution_options(populate_existing=True)
.with_for_update()
.first()
)
monkeypatch.setattr(
'app.services.shipping_notice.intake_service._lock_intake_for_asset_purpose_parser',
_lock_side_effect,
)
def _boom_nested():
class _CM:
def __enter__(self):
raise IntegrityError('stmt', {}, Exception('uq'))
def __exit__(self, *args):
return False
return _CM()
monkeypatch.setattr(db.session, 'begin_nested', _boom_nested)
payload = create_shipping_notice_intake(
user_id=shipping_user.id,
asset_no=asset.asset_no,
conversation_id='conv-race',
)
assert payload['intake_no'] == 'SNI-RACE-WIN'
assert payload['parse_status'] == 'queued'
assert db.session.query(ShippingOrderIntake).filter_by(asset_id=asset.id).count() == 1
def test_create_parse_failed_twice_reuses_single_parse_job(app, shipping_user):
"""parse_failed 并发式连续创建须串行持锁并复用同一 active Job。"""
with app.app_context():
from app.jobs.types import JobType
from app.models import Job
from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(
user_id=shipping_user.id,
upload=_make_upload(b'parse-failed-reuse'),
)
asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
intake = ShippingOrderIntake(
intake_no='SNI-FAIL-REUSE',
asset_id=asset.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parse_failed',
parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
error_code='SHIPPING_NOTICE.INTAKE_PARSE_FAILED',
)
db.session.add(intake)
db.session.commit()
first = create_shipping_notice_intake(
user_id=shipping_user.id,
asset_no=asset.asset_no,
)
second = create_shipping_notice_intake(
user_id=shipping_user.id,
asset_no=asset.asset_no,
)
assert first['intake_no'] == second['intake_no'] == 'SNI-FAIL-REUSE'
assert first['parse_status'] == second['parse_status'] == 'queued'
jobs = (
db.session.query(Job)
.filter(
Job.domain == SHIPPING_NOTICE_JOB_DOMAIN,
Job.job_type == JobType.SHIPPING_NOTICE_PARSE.value,
Job.business_ref == 'SNI-FAIL-REUSE',
Job.status.in_(('queued', 'running')),
)
.all()
)
assert len(jobs) == 1
refreshed = db.session.query(ShippingOrderIntake).filter_by(intake_no='SNI-FAIL-REUSE').one()
assert refreshed.parse_job_id == jobs[0].id
def test_create_intake_ignores_old_parser_version_reuse(app, shipping_user):
"""同一 FileAsset 上旧 parser_version 的 parsed Intake 不得被新版本直接复用。"""
with app.app_context():
app.config['SHIPPING_NOTICE_PARSER_VERSION'] = 'v6'
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(user_id=shipping_user.id, upload=_make_upload(b'legacy-v5-body'))
asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
# 覆盖本次升级:v5 仅有 JSON 附件摘要,无 Document/Candidate/派生资产,须强制重解析
old = ShippingOrderIntake(
intake_no='SNI-OLD-PARSER-V5',
asset_id=asset.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsed',
parser_version='v5',
extracted_text='stale without documents candidates or derived assets',
structured_result_json={'attachment_count': 0, 'attachments': [], 'warnings': []},
)
db.session.add(old)
db.session.commit()
with patch('app.services.shipping_notice.intake_service.enqueue', return_value=909) as enq:
payload = create_shipping_notice_intake(
user_id=shipping_user.id,
asset_no=asset.asset_no,
conversation_id='conv-parser-bump',
)
enq.assert_called_once()
assert payload['intake_no'] != old.intake_no
assert payload['parse_status'] == 'queued'
assert payload['parser_version'] == 'v6'
created = db.session.query(ShippingOrderIntake).filter_by(intake_no=payload['intake_no']).one()
assert created.parser_version == 'v6'
assert created.asset_id == asset.id
# 旧版行仍在,但未被返回/复用
assert db.session.get(ShippingOrderIntake, old.id).parse_status == 'parsed'
def test_error_classes_accept_custom_code_kwargs(app):
"""业务异常支持 code= 关键字,避免新分支抛 TypeError → 500。"""
with app.app_context():
err = NotFoundError(code='FILE_ASSET.NOT_FOUND', message='文件资产不存在')
assert err.code == 'FILE_ASSET.NOT_FOUND'
err2 = ForbiddenError(code='FILE_ASSET.FORBIDDEN', message='无权访问')
assert err2.code == 'FILE_ASSET.FORBIDDEN'
err3 = ValidationError(code='FILE_ASSET.EXPIRED', message='已过期')
assert err3.code == 'FILE_ASSET.EXPIRED'
def test_revision_conflict_when_successor_exists(app, shipping_user):
"""已有后继修订时,再次 create_revision 应冲突。"""
from app.services.shipping_notice.intake_parse_workflow import intake_to_notice_item
with app.app_context():
base = ShippingNotice(
task_no='SN-REV-LOCK-BASE',
user_id=shipping_user.id,
source_type='manual',
upload_status='uploaded',
document_version=1,
)
db.session.add(base)
db.session.flush()
successor = ShippingNotice(
task_no='SN-REV-LOCK-V2',
user_id=shipping_user.id,
source_type='manual',
document_version=2,
supersedes_task_id=base.id,
duplicate_resolution_type='revision',
)
db.session.add(successor)
asset, intake = _seed_parsed_intake(
shipping_user.id, intake_no='SNI-REV-LOCK', hash_value='hash-rev-lock'
)
intake.duplicate_resolution = 'create_revision'
intake.duplicate_target_task_no = base.task_no
db.session.commit()
with pytest.raises(ConflictError) as excinfo:
intake_to_notice_item(intake, asset)
assert excinfo.value.code == 'SHIPPING_NOTICE.REVISION_CONFLICT'
def test_retry_parse_allows_incomplete_parsed_intake(app, shipping_user):
"""附件不完整但顶层 parsed 时须允许重试解析。"""
from app.services.shipping_notice.intake_service import retry_intake_parse
with app.app_context():
_, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-RETRY-INCOMPLETE')
intake.structured_result_json = {
'attachment_count': 1,
'attachments': [{'filename': 'x.pdf', 'parse_status': 'failed', 'warnings': []}],
'warnings': [],
}
db.session.commit()
with patch('app.services.shipping_notice.intake_service.enqueue', return_value=4242) as enq:
payload = retry_intake_parse(user_id=shipping_user.id, intake_no=intake.intake_no)
enq.assert_called_once()
kwargs = enq.call_args.kwargs
assert kwargs.get('commit') is False
assert kwargs.get('dedupe_statuses') == ('queued',)
assert payload['parse_status'] == 'queued'
refreshed = db.session.get(ShippingOrderIntake, intake.id)
assert refreshed.parse_status == 'queued'
assert refreshed.parse_job_id == 4242
def test_retry_parse_does_not_reuse_running_job(app, shipping_user):
"""重试不得复用仍为 running 的原 Job,须新建 queued Job。"""
from app.jobs.types import JobType
from app.models import Job
from app.services.shipping_notice.intake_service import retry_intake_parse
from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
with app.app_context():
_, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-RETRY-RUNNING')
intake.parse_status = 'parse_failed'
db.session.flush()
running = Job(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='running',
priority=0,
business_ref=intake.intake_no,
payload_json={'intake_no': intake.intake_no},
progress=50,
message='running old parse',
attempts=1,
max_attempts=3,
created_by_id=shipping_user.id,
)
db.session.add(running)
db.session.commit()
old_id = int(running.id)
payload = retry_intake_parse(user_id=shipping_user.id, intake_no=intake.intake_no)
assert payload['parse_status'] == 'queued'
refreshed = db.session.get(ShippingOrderIntake, intake.id)
assert int(refreshed.parse_job_id or 0) != old_id
new_job = db.session.get(Job, int(refreshed.parse_job_id))
assert new_job is not None
assert new_job.status == 'queued'
assert db.session.get(Job, old_id).status == 'running'
def test_create_intake_rejects_cancelled_and_expired(app, shipping_user):
"""创建入口不得复活 cancelled/expired;过期须落 expired 并 CONFLICT。"""
from datetime import datetime, timedelta
from app.core.errors import ConflictError
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_cancelled = upload_file_asset(
user_id=shipping_user.id,
upload=_make_upload(b'create-cancel'),
)
asset_expired = upload_file_asset(
user_id=shipping_user.id,
upload=_make_upload(b'create-expire'),
)
a1 = db.session.query(FileAsset).filter_by(asset_no=asset_cancelled['asset_no']).one()
a2 = db.session.query(FileAsset).filter_by(asset_no=asset_expired['asset_no']).one()
cancelled = ShippingOrderIntake(
intake_no='SNI-CREATE-CANCELLED',
asset_id=a1.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='cancelled',
parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
)
expired = ShippingOrderIntake(
intake_no='SNI-CREATE-EXPIRED',
asset_id=a2.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parse_failed',
parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
expires_at=datetime.utcnow() - timedelta(hours=1),
)
db.session.add_all([cancelled, expired])
db.session.commit()
with pytest.raises(ConflictError) as cancelled_exc:
create_shipping_notice_intake(
user_id=shipping_user.id,
asset_no=a1.asset_no,
)
assert cancelled_exc.value.code == 'SHIPPING_NOTICE.INTAKE_INVALID_STATUS'
assert (
db.session.query(ShippingOrderIntake)
.filter_by(intake_no='SNI-CREATE-CANCELLED')
.one()
.parse_status
== 'cancelled'
)
with pytest.raises(ConflictError) as expired_exc:
create_shipping_notice_intake(
user_id=shipping_user.id,
asset_no=a2.asset_no,
)
assert expired_exc.value.code == 'SHIPPING_NOTICE.INTAKE_EXPIRED'
assert (
db.session.query(ShippingOrderIntake)
.filter_by(intake_no='SNI-CREATE-EXPIRED')
.one()
.parse_status
== 'expired'
)
def test_cancel_intake_is_idempotent_and_clears_stage2_projection(app, shipping_user):
"""二次取消不得再释放引用;并清理 parse_summary 阶段二投影。"""
from app.services.file_assets.service import mark_asset_referenced
from app.services.shipping_notice.intake_service import cancel_intake
with app.app_context():
parent = FileAsset(
asset_no='FA-CANCEL-IDEMP-PARENT',
owner_user_id=shipping_user.id,
original_filename='c.eml',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{shipping_user.id}/cancel-idemp/parent.eml',
content_hash='cancel-idemp-parent',
file_size=10,
mime_type='message/rfc822',
upload_status='ready',
lifecycle_status='temporary',
reference_count=0,
asset_role='upload',
)
db.session.add(parent)
db.session.flush()
child = FileAsset(
asset_no='FA-CANCEL-IDEMP-CHILD',
owner_user_id=shipping_user.id,
parent_asset_id=parent.id,
asset_role='derived_attachment',
original_filename='c.pdf',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{shipping_user.id}/cancel-idemp/c.pdf',
content_hash='cancel-idemp-child',
file_size=20,
mime_type='application/pdf',
upload_status='ready',
lifecycle_status='temporary',
reference_count=0,
)
db.session.add(child)
db.session.flush()
mark_asset_referenced(child)
intake = ShippingOrderIntake(
intake_no='SNI-CANCEL-IDEMP',
asset_id=parent.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsed',
parser_version='v6',
structured_result_json={
'document_count': 2,
'candidate_count': 1,
'attachments': [
{
'attachment_key': 'att-001',
'filename': 'c.pdf',
'asset_no': child.asset_no,
'document_id': 99,
}
],
},
)
db.session.add(intake)
db.session.flush()
doc = ShippingOrderDocument(
intake_id=intake.id,
attachment_key='att-001',
document_type='attachment',
filename='c.pdf',
asset_id=child.id,
classification='order_notice',
parse_status='parsed',
)
db.session.add(doc)
db.session.commit()
cancel_intake(user_id=shipping_user.id, intake_no='SNI-CANCEL-IDEMP')
cancel_intake(user_id=shipping_user.id, intake_no='SNI-CANCEL-IDEMP')
db.session.expire_all()
child2 = db.session.get(FileAsset, child.id)
intake2 = db.session.query(ShippingOrderIntake).filter_by(intake_no='SNI-CANCEL-IDEMP').one()
assert int(child2.reference_count or 0) == 0
assert intake2.parse_status == 'cancelled'
summary = intake2.structured_result_json or {}
assert 'document_count' not in summary
assert 'candidate_count' not in summary
att0 = (summary.get('attachments') or [{}])[0]
assert 'asset_no' not in att0
assert 'document_id' not in att0
def test_retry_parse_rejects_cancelled_intake(app, shipping_user):
"""已取消 Intake 不得被重试覆盖回 queued。"""
from app.services.shipping_notice.intake_service import retry_intake_parse
with app.app_context():
parent = FileAsset(
asset_no='FA-RETRY-CANCELLED',
owner_user_id=shipping_user.id,
original_filename='r.eml',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{shipping_user.id}/retry-cancelled.eml',
content_hash='retry-cancelled',
file_size=10,
mime_type='message/rfc822',
upload_status='ready',
lifecycle_status='temporary',
reference_count=0,
asset_role='upload',
)
db.session.add(parent)
db.session.flush()
intake = ShippingOrderIntake(
intake_no='SNI-RETRY-CANCELLED',
asset_id=parent.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='cancelled',
parser_version='v6',
)
db.session.add(intake)
db.session.commit()
with pytest.raises(ConflictError) as excinfo:
retry_intake_parse(user_id=shipping_user.id, intake_no='SNI-RETRY-CANCELLED')
assert excinfo.value.code == 'SHIPPING_NOTICE.INTAKE_INVALID_STATUS'
db.session.expire_all()
assert (
db.session.query(ShippingOrderIntake)
.filter_by(intake_no='SNI-RETRY-CANCELLED')
.one()
.parse_status
== 'cancelled'
)
def test_refresh_duplicate_rejects_cancelled_intake(app, shipping_user):
"""重复刷新持锁后发现已取消须拒绝,不得改写 Candidate。"""
from app.services.shipping_notice.intake_service import refresh_intake_duplicate_detection
with app.app_context():
parent = FileAsset(
asset_no='FA-REFRESH-CANCELLED',
owner_user_id=shipping_user.id,
original_filename='x.eml',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{shipping_user.id}/refresh-cancelled.eml',
content_hash='refresh-cancelled',
file_size=10,
mime_type='message/rfc822',
upload_status='ready',
lifecycle_status='temporary',
reference_count=0,
asset_role='upload',
)
db.session.add(parent)
db.session.flush()
intake = ShippingOrderIntake(
intake_no='SNI-REFRESH-CANCELLED',
asset_id=parent.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='cancelled',
parser_version='v6',
)
db.session.add(intake)
db.session.commit()
with pytest.raises(ConflictError) as excinfo:
refresh_intake_duplicate_detection(
user_id=shipping_user.id,
intake_no='SNI-REFRESH-CANCELLED',
)
assert excinfo.value.code == 'SHIPPING_NOTICE.INTAKE_INVALID_STATUS'
def test_intake_status_api_strips_texts_detail_returns_full(app, client):
"""
Flask 路由:POST /intakes/status 不返回附件全文;GET 详情返回全文;越权 404。
"""
from datetime import datetime, timedelta
from app.core.auth.jwt import issue_local_access_token
from app.models import FileAsset, ShippingOrderIntake, User
with app.app_context():
owner = User(username='intake-api-owner', email='intake-api-owner@example.com', password_hash='x')
other = User(username='intake-api-other', email='intake-api-other@example.com', password_hash='x')
db.session.add_all([owner, other])
db.session.commit()
owner_id = owner.id
other_id = other.id
owner_headers = {'Authorization': f'Bearer {issue_local_access_token(owner)}'}
other_headers = {'Authorization': f'Bearer {issue_local_access_token(other)}'}
asset = FileAsset(
asset_no='FA-EML-API-001',
owner_user_id=owner_id,
original_filename='multi.eml',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{owner_id}/test/multi.eml',
content_hash='hash-eml-api-001',
file_size=12,
mime_type='message/rfc822',
upload_status='ready',
lifecycle_status='temporary',
reference_count=0,
)
db.session.add(asset)
db.session.flush()
intake = ShippingOrderIntake(
intake_no='SNI-EML-API-001',
asset_id=asset.id,
user_id=owner_id,
purpose='shipping_notice',
parse_status='parsed',
parser_version='v2',
extracted_text='flat body',
structured_result_json={
'email': {
'subject': 'API EML',
'body_text': 'SECRET-BODY-TEXT',
'body_text_length': 16,
'stored_body_text_length': 16,
},
'attachment_count': 1,
'attachment_registered_count': 1,
'attachments': [
{
'attachment_key': 'att-001',
'filename': 'order.txt',
'parse_status': 'parsed',
'extracted_text': 'SECRET-ATTACHMENT-TEXT',
'text_length': 22,
'stored_text_length': 22,
}
],
'warnings': [],
},
expires_at=datetime.utcnow() + timedelta(hours=24),
)
db.session.add(intake)
db.session.commit()
status_res = client.post(
'/api/workspace/shipping-notice/intakes/status',
json={'intake_nos': ['SNI-EML-API-001']},
headers=owner_headers,
)
assert status_res.status_code == 200
status_payload = status_res.get_json()
assert status_payload['success'] is True
item = status_payload['data']['items'][0]
summary = item['parse_summary']
assert 'extracted_text' not in (summary.get('attachments') or [{}])[0]
assert 'body_text' not in (summary.get('email') or {})
detail_res = client.get(
'/api/workspace/shipping-notice/intakes/SNI-EML-API-001',
headers=owner_headers,
)
assert detail_res.status_code == 200
detail = detail_res.get_json()['data']
detail_summary = detail['parse_summary']
assert detail_summary['email']['body_text'] == 'SECRET-BODY-TEXT'
assert detail_summary['attachments'][0]['extracted_text'] == 'SECRET-ATTACHMENT-TEXT'
forbidden = client.get(
'/api/workspace/shipping-notice/intakes/SNI-EML-API-001',
headers=other_headers,
)
assert forbidden.status_code in {403, 404}
assert forbidden.get_json().get('success') is False
# 避免未使用变量告警
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'