import uuid from sqlalchemy import ( Column, DateTime, Enum, ForeignKey, Integer, Unicode, UniqueConstraint, text, ) from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.orm import relationship from .kot import Kot from .meta import Base from .voucher_type import VoucherType class Voucher(Base): __tablename__ = "vouchers" __table_args__ = (UniqueConstraint("bill_id", "voucher_type"),) id = Column( "id", UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), default=uuid.uuid4 ) date = Column("date", DateTime, nullable=False, index=True) pax = Column("pax", Integer, nullable=False) bill_id = Column("bill_id", Integer) kot_id = Column("kot_id", Integer, nullable=False, unique=True) creation_date = Column("creation_date", DateTime(), nullable=False) last_edit_date = Column("last_edit_date", DateTime(), nullable=False) food_table_id = Column( "food_table_id", UUID(as_uuid=True), ForeignKey("food_tables.id"), nullable=False, ) customer_id = Column("customer_id", UUID(as_uuid=True), ForeignKey("customers.id")) narration = Column("narration", Unicode(1000), nullable=True) reason = Column("reason", Unicode(255)) voucher_type = Column("voucher_type", Enum(VoucherType), nullable=False) user_id = Column("user_id", UUID(as_uuid=True), ForeignKey("users.id"), nullable=False) user = relationship("User", backref="vouchers") food_table = relationship("FoodTable", backref="vouchers") customer = relationship("Customer", backref="vouchers") kots = relationship( "Kot", backref="voucher", cascade="delete, delete-orphan", cascade_backrefs=False, order_by=Kot.date, ) settlements = relationship( "Settlement", backref="voucher", cascade="delete, delete-orphan", cascade_backrefs=False, ) reprints = relationship( "Reprint", backref="voucher", cascade="delete, delete-orphan", cascade_backrefs=False, ) def __init__( self, date, pax, bill_id, kot_id, food_table_id, customer_id, voucher_type, user_id, ): self.date = date self.pax = pax self.creation_date = date self.last_edit_date = date self.bill_id = bill_id self.kot_id = kot_id self.food_table_id = food_table_id self.customer_id = customer_id self.narration = None self.voucher_type = voucher_type self.user_id = user_id @property def full_bill_id(self): if self.voucher_type == VoucherType.KOT: return "K-" + str(self.kot_id) if self.voucher_type == VoucherType.NO_CHARGE: return "NC-" + str(self.bill_id) if self.voucher_type == VoucherType.STAFF: return "ST-" + str(self.bill_id) if self.voucher_type == VoucherType.REGULAR_BILL: return str(self.bill_id // 10000) + "-" + str(self.bill_id % 10000) if self.voucher_type == VoucherType.VOID: return "K-" + str(self.kot_id) else: raise Exception @property def amount(self): return round(sum(i.amount for k in self.kots for i in k.inventories), 2)