feat(shipping-order): 增加客户事实、编辑窗口与正式通知创建服务
This commit is contained in:
1 parent
4e8b2f8db2
commit
bffcd55b40
17 files changed
+738
-486
No files matched your search
@@ -16,7 +16,8 @@ from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingBusinessSequence,
|
||||
ShippingNotice,
|
||||
ShippingNotice, ShippingOrderTask, ShippingOrderExtraction,
|
||||
ShippingOrderSchema, ShippingOrderSchemaVersion,
|
||||
ShippingCustomer,
|
||||
ShippingCustomerExternalRef,
|
||||
ShippingCustomerIdentifier,
|
||||
@@ -53,6 +54,41 @@ def _context_field() -> ShippingOrderField:
|
||||
return ShippingOrderField.query.filter_by(field_code='bill_to_customer').one()
|
||||
|
||||
|
||||
def _notice_for_customer(customer: ShippingCustomer, task_no: str) -> ShippingNotice:
|
||||
"""按当前事实链构造带客户引用的正式 Notice,避免写入已删除的 Notice.customer_id。"""
|
||||
schema = ShippingOrderSchema(
|
||||
schema_code=f'LIFECYCLE-{task_no}',
|
||||
display_name='生命周期测试 Schema',
|
||||
status='active',
|
||||
)
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id,
|
||||
version=1,
|
||||
status='published',
|
||||
definition_json={'fields': []},
|
||||
checksum='lifecycle-test',
|
||||
)
|
||||
task = ShippingOrderTask(task_no=f'OT-{task_no}', user_id=1, status='completed')
|
||||
db.session.add_all([version, task])
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=task.id,
|
||||
schema_version_id=version.id,
|
||||
input_snapshot_hash=f'{task_no:0<64}'[:64],
|
||||
status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
task.current_order_extraction_id = extraction.id
|
||||
from tests.conftest import confirm_test_customer_resolution
|
||||
confirm_test_customer_resolution(task, customer=customer, extraction=extraction)
|
||||
notice = ShippingNotice(task_no=task_no, order_task_id=task.id)
|
||||
db.session.add(notice)
|
||||
return notice
|
||||
|
||||
|
||||
def test_unused_customer_can_delete_and_identifiers_are_cascade_only(app):
|
||||
"""仅有识别证据的误建客户可删除,证据不应成为业务阻断引用。"""
|
||||
with app.app_context():
|
||||
@@ -74,15 +110,13 @@ def test_unused_customer_can_delete_and_identifiers_are_cascade_only(app):
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reference_kind', [
|
||||
'notice', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match',
|
||||
'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match',
|
||||
])
|
||||
def test_business_and_audit_references_block_delete(app, reference_kind: str):
|
||||
"""每类业务或识别审计引用都必须在统一影响结果中阻断永久删除。"""
|
||||
with app.app_context():
|
||||
customer = _customer()
|
||||
if reference_kind == 'notice':
|
||||
db.session.add(ShippingNotice(task_no='SN-LIFECYCLE', customer_id=customer.id))
|
||||
elif reference_kind == 'sequence':
|
||||
if reference_kind == 'sequence':
|
||||
db.session.add(ShippingBusinessSequence(customer_id=customer.id, business_date=date(2026, 7, 16)))
|
||||
elif reference_kind == 'external_ref':
|
||||
db.session.add(ShippingCustomerExternalRef(customer_id=customer.id, source_system='ERP', legacy_customer_key='C-1'))
|
||||
@@ -201,7 +235,7 @@ def test_delete_rechecks_every_lifecycle_blocker(app, reference_kind: str):
|
||||
with app.app_context():
|
||||
customer = _customer('BLK')
|
||||
if reference_kind == 'notice':
|
||||
db.session.add(ShippingNotice(task_no='SN-DELETE-BLOCK', customer_id=customer.id))
|
||||
_notice_for_customer(customer, 'SN-DELETE-BLOCK')
|
||||
elif reference_kind == 'sequence':
|
||||
db.session.add(ShippingBusinessSequence(customer_id=customer.id, business_date=date(2026, 7, 16)))
|
||||
elif reference_kind == 'external_ref':
|
||||
@@ -267,7 +301,7 @@ def test_delete_blocks_reference_created_after_preview(app):
|
||||
preview = get_customer_lifecycle_impact(customer.id)
|
||||
assert preview['can_delete'] is True
|
||||
|
||||
db.session.add(ShippingNotice(task_no='SN-DELETE-RACE', customer_id=customer.id))
|
||||
_notice_for_customer(customer, 'SN-DELETE-RACE')
|
||||
db.session.commit()
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
delete_customer(customer.id, confirmation_short_code='RCE', reason='误建', actor_id=None)
|
||||
|
||||
@@ -26,7 +26,8 @@ from app.models import (
|
||||
ShippingCustomerMerge,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingOrderField,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderTask,
|
||||
ShippingOrderExtraction,
|
||||
)
|
||||
from app.services.admin.shipping_customer_lifecycle_service import get_customer_lifecycle_impact
|
||||
from app.services.admin.shipping_customer_merge_service import get_customer_merge_impact, merge_customer
|
||||
@@ -52,6 +53,30 @@ def _context_field() -> ShippingOrderField:
|
||||
return ShippingOrderField.query.filter_by(field_code='bill_to_customer').one()
|
||||
|
||||
|
||||
def _notice_with_customer_history(customer: ShippingCustomer) -> ShippingNotice:
|
||||
"""按 OT→Resolution 构造历史 Notice 客户事实。"""
|
||||
schema = ShippingOrderSchema(schema_code='MERGE-HISTORY', display_name='归并历史测试', status='active')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={'fields': []}, checksum='merge-history',
|
||||
)
|
||||
task = ShippingOrderTask(task_no='OT-SN-MERGE-HISTORY', user_id=1, status='completed')
|
||||
db.session.add_all([version, task])
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=task.id, schema_version_id=version.id, input_snapshot_hash='m' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
task.current_order_extraction_id = extraction.id
|
||||
from tests.conftest import confirm_test_customer_resolution
|
||||
confirm_test_customer_resolution(task, customer=customer, extraction=extraction)
|
||||
notice = ShippingNotice(task_no='SN-MERGE-HISTORY', business_no='SRC26071601', order_task_id=task.id)
|
||||
db.session.add(notice)
|
||||
return notice
|
||||
|
||||
|
||||
def test_merge_moves_future_configuration_and_preserves_history(app):
|
||||
"""归并迁移证据和来源键,但业务单、流水及其客户快照始终保留源客户。"""
|
||||
with app.app_context():
|
||||
@@ -71,10 +96,7 @@ def test_merge_moves_future_configuration_and_preserves_history(app):
|
||||
normalized_value='same@example.com', status='approved', source='manual',
|
||||
),
|
||||
ShippingCustomerExternalRef(customer_id=source.id, source_system='ERP', legacy_customer_key='LEGACY-SRC'),
|
||||
ShippingNotice(
|
||||
task_no='SN-MERGE-HISTORY', customer_id=source.id, business_no='SRC26071601',
|
||||
customer_name_snapshot=source.standard_name, customer_short_code_snapshot=source.short_code,
|
||||
),
|
||||
_notice_with_customer_history(source),
|
||||
ShippingBusinessSequence(customer_id=source.id, business_date=date(2026, 7, 16), current_value=1),
|
||||
])
|
||||
db.session.commit()
|
||||
@@ -106,9 +128,12 @@ def test_merge_moves_future_configuration_and_preserves_history(app):
|
||||
assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=target_id).count() == 2
|
||||
assert db.session.query(ShippingCustomerExternalRef).filter_by(customer_id=target_id).count() == 1
|
||||
historical_notice = db.session.query(ShippingNotice).filter_by(task_no='SN-MERGE-HISTORY').one()
|
||||
assert historical_notice.customer_id == source_id
|
||||
historical_task = db.session.get(ShippingOrderTask, historical_notice.order_task_id)
|
||||
historical_resolution = ShippingCustomerShadowResolution.query.filter_by(
|
||||
candidate_id=historical_task.candidate_id,
|
||||
).one()
|
||||
assert historical_resolution.confirmed_customer_id == source_id
|
||||
assert historical_notice.business_no == 'SRC26071601'
|
||||
assert historical_notice.customer_short_code_snapshot == 'SRC'
|
||||
assert db.session.query(ShippingBusinessSequence).filter_by(customer_id=source_id).count() == 1
|
||||
merge = db.session.get(ShippingCustomerMerge, result['merge_id'])
|
||||
assert merge is not None and merge.source_customer_id_snapshot == source_id
|
||||
|
||||
@@ -13,7 +13,11 @@ from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import ShippingCustomer, ShippingCustomerIdentifier, ShippingCustomerLifecycleEvent, ShippingNotice
|
||||
from app.models import (
|
||||
ShippingCustomer, ShippingCustomerIdentifier, ShippingCustomerLifecycleEvent, ShippingNotice,
|
||||
ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion,
|
||||
ShippingOrderTask,
|
||||
)
|
||||
from app.services.admin.shipping_customer_service import (
|
||||
create_customer,
|
||||
create_identifier,
|
||||
@@ -28,6 +32,30 @@ def _create_customer(*, name: str = '无锡宇辰有限公司', short_code: str
|
||||
return create_customer({'standard_name': name, 'short_code': short_code}, actor_id=None)
|
||||
|
||||
|
||||
def _notice_for_customer(customer_id: int) -> ShippingNotice:
|
||||
"""按正式客户事实链创建 Notice,列表统计不得依赖已删除的 Notice.customer_id。"""
|
||||
schema = ShippingOrderSchema(schema_code='CUSTOMER-LIST', display_name='客户列表测试', status='active')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={'fields': []}, checksum='customer-list',
|
||||
)
|
||||
task = ShippingOrderTask(task_no='OT-CUSTOMER-LIST', user_id=1, status='completed')
|
||||
db.session.add_all([version, task])
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=task.id, schema_version_id=version.id, input_snapshot_hash='c' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
task.current_order_extraction_id = extraction.id
|
||||
from tests.conftest import confirm_test_customer_resolution
|
||||
confirm_test_customer_resolution(task, customer=db.session.get(ShippingCustomer, customer_id), extraction=extraction)
|
||||
notice = ShippingNotice(task_no='SN-COUNT-1', order_task_id=task.id)
|
||||
db.session.add(notice)
|
||||
return notice
|
||||
|
||||
|
||||
def test_customer_short_code_is_normalized_and_unique(app):
|
||||
"""简码统一转大写,且标准化后重复必须返回冲突。"""
|
||||
with app.app_context():
|
||||
@@ -219,7 +247,7 @@ def test_customer_list_returns_preaggregated_reference_counts(app):
|
||||
"""列表返回业务单和识别证据数量,避免管理端逐客户补查。"""
|
||||
with app.app_context():
|
||||
customer = _create_customer()
|
||||
db.session.add(ShippingNotice(task_no='SN-COUNT-1', customer_id=customer['id']))
|
||||
_notice_for_customer(customer['id'])
|
||||
db.session.add(ShippingCustomerIdentifier(
|
||||
customer_id=customer['id'],
|
||||
identifier_type='name_alias',
|
||||
|
||||
@@ -22,6 +22,11 @@ from app.models import (
|
||||
ShippingOrderField,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderTask,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingNotice,
|
||||
User,
|
||||
)
|
||||
@@ -65,6 +70,98 @@ def _headers(username: str, role: str) -> dict[str, str]:
|
||||
return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'}
|
||||
|
||||
|
||||
def _notice_with_customer(*, task_no: str, customer_id: int, business_no: str | None = None) -> ShippingNotice:
|
||||
"""创建由已确认客户识别结果支撑的正式 Notice,避免回写 bill_to 或旧匹配表。"""
|
||||
_identity_field()
|
||||
user = User.query.filter_by(username='shipping-admin').one()
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').order_by(
|
||||
ShippingOrderSchemaVersion.id.desc(),
|
||||
).first()
|
||||
asset = FileAsset(
|
||||
asset_no=f'FA-{task_no}', owner_user_id=user.id, original_filename='notice.pdf',
|
||||
storage_provider='minio', storage_bucket='test', storage_key=f'{task_no}.pdf',
|
||||
content_hash=f'{task_no:0<64}'[:64], file_size=1, upload_status='uploaded', lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingOrderIntake(
|
||||
intake_no=f'INTAKE-{task_no}', asset_id=asset.id, user_id=user.id, parser_version='v6', parse_status='parsed',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
document = ShippingOrderDocument(
|
||||
intake_id=intake.id, asset_id=asset.id, document_type='attachment', attachment_key='file',
|
||||
filename='notice.pdf', classification='order_notice', parse_status='parsed',
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no=f'CANDIDATE-{task_no}', intake_id=intake.id, primary_document_id=document.id,
|
||||
candidate_key='document:1', validation_status='ready', selected=True,
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
task = ShippingOrderTask(
|
||||
task_no=task_no, user_id=user.id, intake_id=intake.id, candidate_id=candidate.id,
|
||||
status='ready', current_step='customer_review',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=task.id,
|
||||
schema_version_id=version.id,
|
||||
input_snapshot_hash=('a' * 64),
|
||||
status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
task.current_order_extraction_id = extraction.id
|
||||
candidate.order_extraction_id = extraction.id
|
||||
db.session.add(ShippingCustomerShadowResolution(
|
||||
candidate_id=candidate.id,
|
||||
intake_id=intake.id,
|
||||
resolution_version='test-v1',
|
||||
status='confirmed',
|
||||
evidence_json=[],
|
||||
candidate_matches_json=[],
|
||||
confirmed_customer_id=customer_id,
|
||||
confirmation_method='manual',
|
||||
))
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=task.id,
|
||||
extraction_id=extraction.id,
|
||||
schema_version_id=version.id,
|
||||
order_data_version=1,
|
||||
header_values_json={},
|
||||
source_manifest_json={},
|
||||
rule_versions_json={},
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
task.order_snapshot_id = snapshot.id
|
||||
snapshot_line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id,
|
||||
position=0,
|
||||
line_no=1,
|
||||
part_number='TEST-PART',
|
||||
qty=1,
|
||||
)
|
||||
db.session.add(snapshot_line)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id,
|
||||
snapshot_line_id=snapshot_line.id,
|
||||
line_no=1,
|
||||
match_result='matched',
|
||||
inventory_status='ready',
|
||||
is_current=True,
|
||||
))
|
||||
notice = ShippingNotice(task_no=task_no, business_no=business_no, order_task_id=task.id)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
return notice
|
||||
|
||||
|
||||
def test_shipping_customer_admin_crud_uses_standard_contract(app, client):
|
||||
"""管理员可创建和查询客户,校验失败返回标准错误 envelope。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
@@ -327,7 +424,7 @@ def test_shipping_customer_delete_api_rejects_invalid_confirmation_and_blockers(
|
||||
customer = ShippingCustomer(standard_name='有业务客户', short_code='BLK', status='active')
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNotice(task_no='SN-DELETE-API', customer_id=customer.id))
|
||||
_notice_with_customer(task_no='SN-DELETE-API', customer_id=customer.id)
|
||||
db.session.commit()
|
||||
customer_id = customer.id
|
||||
|
||||
@@ -346,7 +443,7 @@ def test_shipping_customer_delete_api_rejects_invalid_confirmation_and_blockers(
|
||||
assert blocked.status_code == 409
|
||||
error = parse_api_error(blocked.get_json())
|
||||
assert error['code'] == 'SHIPPING.CUSTOMER_DELETE_BLOCKED'
|
||||
assert error['details']['blockers']['business_cases'] == 1
|
||||
assert error['details']['blockers']['shipping_notices'] == 1
|
||||
|
||||
|
||||
def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history(app, client):
|
||||
@@ -363,7 +460,7 @@ def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history(
|
||||
customer_id=source.id, identifier_type='name_alias', raw_value='Source Alias',
|
||||
normalized_value='SOURCEALIAS', status='approved', source='manual',
|
||||
),
|
||||
ShippingNotice(task_no='SN-MERGE-API', customer_id=source.id, business_no='SRC26071601'),
|
||||
_notice_with_customer(task_no='SN-MERGE-API', customer_id=source.id, business_no='SRC26071601'),
|
||||
])
|
||||
db.session.commit()
|
||||
source_id = source.id
|
||||
@@ -382,7 +479,7 @@ def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history(
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert preview.status_code == 200
|
||||
assert parse_api_data(preview.get_json())['historical_references']['business_cases'] == 1
|
||||
assert parse_api_data(preview.get_json())['historical_references']['shipping_notices'] == 1
|
||||
|
||||
response = client.post(
|
||||
f'/api/admin/shipping-customers/{source_id}/merge',
|
||||
@@ -396,7 +493,10 @@ def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history(
|
||||
with app.app_context():
|
||||
assert db.session.get(ShippingCustomer, source_id).status == 'merged'
|
||||
assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=target_id).count() == 1
|
||||
assert db.session.query(ShippingNotice).filter_by(task_no='SN-MERGE-API').one().customer_id == source_id
|
||||
notice = db.session.query(ShippingNotice).filter_by(task_no='SN-MERGE-API').one()
|
||||
task = db.session.get(ShippingOrderTask, notice.order_task_id)
|
||||
resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
|
||||
assert resolution.confirmed_customer_id == source_id
|
||||
|
||||
|
||||
def test_shipping_customer_merge_api_validates_target_confirmation_and_reason(app, client):
|
||||
@@ -507,47 +607,3 @@ def test_shipping_customer_shadow_report_and_label_api(app, client):
|
||||
headers=_headers('shipping-user', 'user'),
|
||||
)
|
||||
assert forbidden.status_code == 403
|
||||
|
||||
|
||||
def test_shipping_customer_numbered_correction_api_preserves_old_number(app, client):
|
||||
"""管理员纠错 API 作废原号并返回替代新号,普通用户不可调用。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
wrong = ShippingCustomer(standard_name='错误客户', short_code='OLD', status='active')
|
||||
correct = ShippingCustomer(standard_name='正确客户', short_code='NEW', status='active')
|
||||
db.session.add_all([wrong, correct])
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no='SN-CORRECTION-API',
|
||||
source_type='manual', customer_resolution_status='pending',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
from app.services.shipping_notice.customer_identity_gate import confirm_task_customer
|
||||
|
||||
confirm_task_customer(task, customer_id=wrong.id, actor_id=None)
|
||||
old_business_no = task.business_no
|
||||
correct_id = correct.id
|
||||
|
||||
forbidden = client.post(
|
||||
'/api/admin/shipping-customers/numbered-task-correction',
|
||||
json={'task_ref': old_business_no, 'customer_id': correct_id, 'reason': '客户错误'},
|
||||
headers=_headers('shipping-user', 'user'),
|
||||
)
|
||||
assert forbidden.status_code == 403
|
||||
|
||||
response = client.post(
|
||||
'/api/admin/shipping-customers/numbered-task-correction',
|
||||
json={'task_ref': old_business_no, 'customer_id': correct_id, 'reason': '客户错误'},
|
||||
headers=_headers('shipping-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
assert payload['old_business_no'] == old_business_no
|
||||
assert payload['new_business_no'].startswith('NEW')
|
||||
with app.app_context():
|
||||
old_notice = ShippingNotice.query.filter_by(business_no=old_business_no).one()
|
||||
replacement = ShippingNotice.query.filter_by(supersedes_task_id=old_notice.id).one()
|
||||
assert old_notice.lifecycle_status == 'voided'
|
||||
assert replacement.business_no == payload['new_business_no']
|
||||
Reference in new issue
Block a user