from datetime import datetime, timezone, timedelta from app.extensions import db from sqlalchemy.orm import relationship from sqlalchemy.sql import func class Charge(db.Model): __tablename__ = 'charges' id = db.Column(db.Integer, primary_key=True, autoincrement=True) offer_id = db.Column(db.String(50), nullable=False) code = db.Column(db.String(50), nullable=False) percent = db.Column(db.Float, default=0.0) description = db.Column(db.Text, nullable=True) due = db.Column(db.Integer, nullable=False) created_at = db.Column(db.DateTime(timezone=True), server_default=func.now()) updated_at = db.Column(db.DateTime(timezone=True), server_default=func.now(), onupdate=func.now()) # offer = relationship( # "Offer", # primaryjoin="Charge.offer_id == Offer.id", # foreign_keys=[offer_id], # back_populates="charges", # ) @classmethod def add_charges(cls, offer_id, charges): """ Add charges to an offer. Args: offer_id (int): ID of the offer to associate charges with. charges (list): A list of dictionaries with keys: code (str), amount (float), percent (float), description (str), due (int) """ if not charges or not isinstance(charges, list): raise ValueError("Charges must be a non-empty list of dictionaries") if offer_id is None: raise ValueError("offer_id cannot be None") offer_charges = [] for charge in charges: code = charge.get("code") percent = charge.get("percent", 0.0) description = charge.get("description", "") due_days = charge.get("due", 0) existing = cls.query.filter_by(offer_id=offer_id, code=code).first() if existing: continue charge_obj = cls( offer_id = offer_id, code = code, percent = percent, description = description, due = due_days, created_at=datetime.now(timezone.utc), updated_at=datetime.now(timezone.utc) ) db.session.add(charge_obj) offer_charges.append(charge_obj) return offer_charges @classmethod def get_offer_charges(cls, offer_id): """ Get all charges for a particular offer as a dictionary Args: offer_id (str): The offer ID. """ if not offer_id: raise ValueError("offer_id not found") charges = cls.query.filter_by(offer_id=offer_id).all() return charges def to_dict(self): return { 'id': self.id, 'offerId': self.offer_id, 'code': self.code, 'percent': self.percent, 'description': self.description, 'due': self.due } def __repr__(self): return f""