from sqlalchemy import CheckConstraint, Column, Date, DateTime, ForeignKey, Integer, Numeric, String, Text, UniqueConstraint from sqlalchemy.orm import relationship from sqlalchemy.sql import func from app.database.database import Base class Payment(Base): __tablename__ = "payments" id = Column(Integer, primary_key=True, index=True) project_id = Column(Integer, ForeignKey("projects.id"), nullable=False, index=True) date = Column(Date, nullable=False, index=True) document_number = Column(String, nullable=True) amount = Column(Numeric(18, 2), nullable=False) currency = Column(String, nullable=False, default="RUB") comment = Column(Text) status = Column(String, nullable=False, default="active", index=True) created_at = Column(DateTime, nullable=False, server_default=func.now()) updated_at = Column(DateTime, nullable=False, server_default=func.now(), onupdate=func.now()) project = relationship("Project") allocations = relationship("PaymentAllocation", back_populates="payment", cascade="all, delete-orphan") class PaymentAllocation(Base): __tablename__ = "payment_allocations" __table_args__ = ( UniqueConstraint("payment_id", "ks3_id", name="uq_payment_ks3"), CheckConstraint("amount > 0", name="ck_payment_alloc_positive"), ) id = Column(Integer, primary_key=True, index=True) payment_id = Column(Integer, ForeignKey("payments.id", ondelete="CASCADE"), nullable=False, index=True) ks3_id = Column(Integer, ForeignKey("ks3_documents.id"), nullable=False, index=True) amount = Column(Numeric(18, 2), nullable=False) payment = relationship("Payment", back_populates="allocations") ks3 = relationship("KS3")