Files
syops/backend/tests/test_shipping_notice_intakes_lifecycle.py

1003 lines
41 KiB
Python
Raw Permalink 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,
ShippingCustomer,
ShippingCustomerShadowResolution,
ShippingDocumentLayoutVersion,
ShippingOrderCandidate,
ShippingOrderDocument,
ShippingOrderIntake,
ShippingOrderExtraction,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
ShippingNotice,
ShippingOrderTask,
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_active_intake_list_omits_heavy_candidate_review_details(app, shipping_user):
"""活跃列表保留恢复所需字段,但不得传输审核证据与裁决历史。"""
from app.services.shipping_notice.intake_service import list_active_intakes_for_conversation
with app.app_context():
asset, intake = _seed_parsed_intake(
shipping_user.id,
intake_no='SNI-LIGHT-LIST-001',
hash_value='light-list-hash',
)
intake.conversation_id = 'conversation-light-list'
document = ShippingOrderDocument(
intake_id=intake.id,
asset_id=asset.id,
document_type='attachment',
attachment_key='order.pdf',
filename='order.pdf',
content_hash='light-list-document-hash',
classification='order_notice',
parse_status='parsed',
)
db.session.add(document)
db.session.flush()
db.session.add(ShippingOrderCandidate(
candidate_no='SNC-LIGHT-LIST-001',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='light-list-candidate',
structured_result_json={
'business_summary': {'po_number': 'PO-LIGHT-001'},
'extraction': {
'field_adjudication': {'observation_history': ['large-history']},
'customer_matches': [{'customer': 'large-match'}],
},
},
evidence_json=[{'text': 'large-evidence'}],
selected=True,
validation_status='ready',
))
db.session.commit()
rows = list_active_intakes_for_conversation(
user_id=shipping_user.id,
conversation_id='conversation-light-list',
)
assert len(rows) == 1
candidate = rows[0]['candidates'][0]
assert candidate['candidate_no'] == 'SNC-LIGHT-LIST-001'
assert candidate['po_number'] == 'PO-LIGHT-001'
assert candidate['selected'] is True
assert 'evidence' not in candidate
assert 'field_adjudication' not in candidate
assert 'customer_matches' not in candidate
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',
)
# 重复目标由建单前 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,
order_task_id=existing_task_id,
)
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',
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='ready',
conflicts_json=[],
extraction_source='dify_workflow',
selected=True,
)
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},
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 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,
order_task_id=existing_task_id,
))
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_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=[], 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'
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):
# 仅注入一次 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(
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',
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