from datetime import datetime from sqlalchemy import DateTime, Float, ForeignKey, String, Text, UniqueConstraint, Index from sqlalchemy.orm import Mapped, mapped_column from app.models.base import Base, TimestampMixin class Invoice(Base, TimestampMixin): __tablename__ = "invoices" id: Mapped[str] = mapped_column(String(32), primary_key=True) user_id: Mapped[str] = mapped_column( String(32), ForeignKey("users.id", ondelete="CASCADE"), index=True ) invoice_no: Mapped[str] = mapped_column(String(32), unique=True, nullable=False) header_type: Mapped[str] = mapped_column(String(16), nullable=False) header_name: Mapped[str] = mapped_column(String(128), nullable=False) header_tax_no: Mapped[str | None] = mapped_column(String(32), nullable=True) header_register_address: Mapped[str | None] = mapped_column(String(256), nullable=True) header_register_phone: Mapped[str | None] = mapped_column(String(32), nullable=True) header_bank_name: Mapped[str | None] = mapped_column(String(128), nullable=True) header_bank_account: Mapped[str | None] = mapped_column(String(64), nullable=True) email: Mapped[str] = mapped_column(String(128), nullable=False) total_amount: Mapped[float] = mapped_column(Float, nullable=False, default=0) total_credits: Mapped[float] = mapped_column(Float, nullable=False, default=0) status: Mapped[str] = mapped_column(String(16), nullable=False, default="processing") failure_reason: Mapped[str | None] = mapped_column(Text, nullable=True) issued_at: Mapped[datetime | None] = mapped_column( DateTime(timezone=True), nullable=True ) __table_args__ = ( Index('idx_invoices_user_created', 'user_id', 'created_at'), Index('idx_invoices_status_created', 'status', 'created_at'), ) class InvoiceOrder(Base, TimestampMixin): __tablename__ = "invoice_orders" id: Mapped[str] = mapped_column(String(32), primary_key=True) invoice_id: Mapped[str] = mapped_column( String(32), ForeignKey("invoices.id", ondelete="CASCADE"), index=True ) order_id: Mapped[str] = mapped_column( String(32), ForeignKey("payment_orders.id", ondelete="CASCADE"), index=True ) order_no: Mapped[str] = mapped_column(String(64), nullable=False) amount: Mapped[float] = mapped_column(Float, nullable=False, default=0) credits: Mapped[float] = mapped_column(Float, nullable=False, default=0) __table_args__ = ( UniqueConstraint('invoice_id', 'order_id', name='uq_invoice_orders'), Index('idx_invoice_orders_invoice', 'invoice_id'), Index('idx_invoice_orders_order', 'order_id'), )