""" models/shipping_fulfillment_policy.py 用途:保存货代字段能力绑定和不可变履约策略版本。 依赖:订单 Schema、users 与 SQLAlchemy Base。 逻辑:Schema 负责字段目录;本模型以稳定 field_id 将字段绑定到货代履约能力,并只允许一个 published 策略。 """ from __future__ import annotations from datetime import datetime from typing import Any, Optional from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text from sqlalchemy.orm import Mapped, mapped_column from app.models.base import Base class ShippingFulfillmentPolicy(Base): """货代履约策略版本;published 版本不可修改且由冻结 Snapshot 引用。""" __tablename__ = 'shipping_fulfillment_policies' __table_args__ = ( UniqueConstraint('schema_id', 'policy_code', 'version', name='uq_shipping_fulfillment_policies_version'), CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_shipping_fulfillment_policies_status'), Index( 'uq_shipping_fulfillment_policy_one_published', 'schema_id', unique=True, postgresql_where=text("status = 'published'"), sqlite_where=text("status = 'published'"), ), ) id: Mapped[int] = mapped_column(primary_key=True) schema_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schemas.id'), nullable=False) policy_code: Mapped[str] = mapped_column(String(64), nullable=False) version: Mapped[int] = mapped_column(Integer, nullable=False) status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft') definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1') change_note: Mapped[Optional[str]] = mapped_column(Text, nullable=True) source_policy_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_fulfillment_policies.id'), nullable=True) created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) published_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) retired_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)