fix(shipping-notice): 客户简码允许重复解除全局唯一约束
- short_code 去除 unique,新增迁移 sd9e8f7a6b5c 删除唯一约束 - 服务层移除简码唯一校验,导入预检移除撞码 warning - 清理四语言失效错误码,同步 demand/tec/technical 文档描述
This commit is contained in:
1 parent
20835dcfc0
commit
34fe0c4d78
13 files changed
+67
-55
No files matched your search
@@ -37,7 +37,8 @@ class ShippingCustomer(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
standard_name: Mapped[str] = mapped_column(String(200), nullable=False, index=True)
|
||||
short_code: Mapped[str] = mapped_column(String(6), nullable=False, unique=True)
|
||||
# 业务规则:客户简码允许重复(不同标准客户可共用同一简码,仅用作编号前缀),禁止再加唯一约束。
|
||||
short_code: Mapped[str] = mapped_column(String(6), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='active', server_default='active')
|
||||
merged_into_customer_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_customers.id'),
|
||||
|
||||
@@ -153,13 +153,7 @@ def _customer_row_validation(raw: dict[str, Any], *, default_source_system: str)
|
||||
if status not in {'active', 'inactive'}:
|
||||
errors.append({'code': 'SHIPPING.CUSTOMER_STATUS_INVALID', 'field': 'status'})
|
||||
existing_ref = _existing_customer_by_ref(source_system, legacy_key) if legacy_key and source_system else None
|
||||
code_owner = db.session.query(ShippingCustomer).filter_by(short_code=short_code).first() if short_code else None
|
||||
if code_owner and (not existing_ref or code_owner.id != existing_ref.id):
|
||||
warnings.append({
|
||||
'code': 'SHIPPING.CUSTOMER_IMPORT_SHORT_CODE_CONFLICT',
|
||||
'customer_id': code_owner.id,
|
||||
'short_code': short_code,
|
||||
})
|
||||
# 客户简码允许重复(业务规则),导入预检不再因简码撞码产生 warning。
|
||||
normalized_name = normalize_customer_name(name)
|
||||
similar = [
|
||||
item for item in db.session.query(ShippingCustomer).all()
|
||||
|
||||
@@ -320,23 +320,12 @@ def get_customer(customer_id: int) -> dict[str, Any]:
|
||||
return serialize_customer(record, include_identifiers=True)
|
||||
|
||||
|
||||
def _assert_short_code_available(short_code: str, *, exclude_customer_id: int | None = None) -> None:
|
||||
"""校验客户简码全局唯一。"""
|
||||
query = db.session.query(ShippingCustomer.id).filter(ShippingCustomer.short_code == short_code)
|
||||
if exclude_customer_id is not None:
|
||||
query = query.filter(ShippingCustomer.id != exclude_customer_id)
|
||||
if query.first():
|
||||
raise ConflictError(
|
||||
'Customer short code already exists',
|
||||
code='SHIPPING.CUSTOMER_SHORT_CODE_EXISTS',
|
||||
details={'short_code': short_code},
|
||||
)
|
||||
|
||||
|
||||
def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""
|
||||
创建标准客户。
|
||||
|
||||
客户简码允许重复(业务规则),仅做格式归一化,不做唯一性校验。
|
||||
|
||||
Args:
|
||||
data: standard_name、short_code、status、remark。
|
||||
actor_id: 当前管理员 ID。
|
||||
@@ -351,7 +340,6 @@ def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
|
||||
details={'field': 'standard_name'},
|
||||
)
|
||||
short_code = normalize_short_code(data.get('short_code'))
|
||||
_assert_short_code_available(short_code)
|
||||
status = clean_text(data.get('status') or 'active').lower()
|
||||
if status not in CUSTOMER_STATUSES - {'merged'}:
|
||||
raise ValidationError('Invalid customer status', code='SHIPPING.CUSTOMER_STATUS_INVALID')
|
||||
@@ -442,7 +430,6 @@ def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | N
|
||||
next_name = name
|
||||
if 'short_code' in data:
|
||||
next_short_code = normalize_short_code(data.get('short_code'))
|
||||
_assert_short_code_available(next_short_code, exclude_customer_id=customer_id)
|
||||
if 'status' in data:
|
||||
next_status = clean_text(data.get('status')).lower()
|
||||
if next_status not in CUSTOMER_STATUSES - {'merged'}:
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
"""
|
||||
backend/migrations/versions/sd9e8f7a6b5c_allow_duplicate_customer_short_code.py
|
||||
|
||||
用途:放开 shipping_customers.short_code 的全局唯一约束,允许不同标准客户共用简码。
|
||||
依赖:Alembic revision rc3c4d5e6f7a;shipping_customers 表由 f1a2b3c4d5e6 创建。
|
||||
逻辑:实际业务中客户简码可重复(简码仅作业务编号前缀,客户身份以 id/识别证据为准),
|
||||
原 UniqueConstraint('short_code')(未命名,PostgreSQL 默认名
|
||||
shipping_customers_short_code_key)导致新增/改名报「客户简码已存在」。
|
||||
降级前必须先合并或改开重复简码,否则重建唯一约束会因存量重复数据失败。
|
||||
|
||||
Revision ID: sd9e8f7a6b5c
|
||||
Revises: rc3c4d5e6f7a
|
||||
Create Date: 2026-09-21 11:40:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
|
||||
revision = "sd9e8f7a6b5c"
|
||||
down_revision = "rc3c4d5e6f7a"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""删除客户简码的唯一约束,允许重复。"""
|
||||
op.drop_constraint(
|
||||
'shipping_customers_short_code_key', 'shipping_customers', type_='unique',
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""恢复唯一约束;执行前必须先处理存量重复简码,否则约束创建失败。"""
|
||||
op.create_unique_constraint(
|
||||
'shipping_customers_short_code_key', 'shipping_customers', ['short_code'],
|
||||
)
|
||||
@@ -16,7 +16,7 @@ from openpyxl import Workbook
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingCustomerExternalRef,
|
||||
@@ -177,8 +177,8 @@ def test_publish_uses_row_source_system_for_customer_and_identifier(app):
|
||||
assert b'identifier_created' in csv_content
|
||||
|
||||
|
||||
def test_publish_conflict_rolls_back_entire_batch(app):
|
||||
"""发布中出现简码唯一冲突时,客户、来源映射和逐行结果全部回滚。"""
|
||||
def test_publish_allows_duplicate_short_codes(app):
|
||||
"""简码允许重复:同批两行共用简码须整批发布成功,创建两个同简码客户。"""
|
||||
with app.app_context():
|
||||
batch = create_import_batch(
|
||||
_make_upload([
|
||||
@@ -188,12 +188,12 @@ def test_publish_conflict_rolls_back_entire_batch(app):
|
||||
source_system='ERP',
|
||||
actor_id=None,
|
||||
)
|
||||
published = publish_import_batch(batch['id'], actor_id=None)
|
||||
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
publish_import_batch(batch['id'], actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.CUSTOMER_IMPORT_PUBLISH_CONFLICT'
|
||||
assert db.session.query(ShippingCustomer).count() == 0
|
||||
assert db.session.query(ShippingCustomerExternalRef).count() == 0
|
||||
persisted = db.session.get(ShippingCustomerImportBatch, batch['id'])
|
||||
assert persisted.status == 'validated'
|
||||
assert all(row.result_status is None for row in persisted.rows)
|
||||
# 断言整批发布成功且两个客户共用简码 DUP,各自持有独立来源映射
|
||||
assert published['status'] == 'published'
|
||||
customers = db.session.query(ShippingCustomer).filter_by(short_code='DUP').all()
|
||||
assert len(customers) == 2
|
||||
assert {ref.legacy_customer_key for ref in db.session.query(ShippingCustomerExternalRef).all()} == {
|
||||
'ERP-101', 'ERP-102',
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import pytest
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import (
|
||||
ShippingCustomer, ShippingCustomerIdentifier, ShippingCustomerLifecycleEvent, ShippingNotice,
|
||||
ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion,
|
||||
@@ -56,15 +56,16 @@ def _notice_for_customer(customer_id: int) -> ShippingNotice:
|
||||
return notice
|
||||
|
||||
|
||||
def test_customer_short_code_is_normalized_and_unique(app):
|
||||
"""简码统一转大写,且标准化后重复必须返回冲突。"""
|
||||
def test_customer_short_code_is_normalized_and_duplicate_allowed(app):
|
||||
"""简码统一转大写;业务允许不同标准客户共用同一简码,仅格式非法才拒绝。"""
|
||||
with app.app_context():
|
||||
created = _create_customer(short_code='wyc')
|
||||
assert created['short_code'] == 'WYC'
|
||||
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
_create_customer(name='另一客户', short_code='WYC')
|
||||
assert exc_info.value.code == 'SHIPPING.CUSTOMER_SHORT_CODE_EXISTS'
|
||||
# 重复简码(含小写归一后撞码)必须创建成功,不再返回冲突
|
||||
duplicated = _create_customer(name='另一客户', short_code='wyc')
|
||||
assert duplicated['short_code'] == 'WYC'
|
||||
assert db.session.query(ShippingCustomer).filter_by(short_code='WYC').count() == 2
|
||||
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
_create_customer(name='格式错误客户', short_code='W1')
|
||||
|
||||
Reference in new issue
Block a user