Пример #1
0
class DiscountPolicy(BaseScopedNameMixin, db.Model):
    """
    Consists of the discount rules applicable on items

    `title` has a GIN index to enable trigram matching.
    """
    __tablename__ = 'discount_policy'
    __uuid_primary_key__ = True
    __table_args__ = (db.UniqueConstraint('organization_id', 'name'),
        db.UniqueConstraint('organization_id', 'discount_code_base'),
        db.CheckConstraint('percentage > 0 and percentage <= 100', 'discount_policy_percentage_check'),
        db.CheckConstraint('discount_type = 0 or (discount_type = 1 and bulk_coupon_usage_limit IS NOT NULL)', 'discount_policy_bulk_coupon_usage_limit_check'))

    organization_id = db.Column(None, db.ForeignKey('organization.id'), nullable=False)
    organization = db.relationship(Organization, backref=db.backref('discount_policies', order_by='DiscountPolicy.created_at.desc()', lazy='dynamic', cascade='all, delete-orphan'))
    parent = db.synonym('organization')

    discount_type = db.Column(db.Integer, default=DISCOUNT_TYPE.AUTOMATIC, nullable=False)

    # Minimum number of a particular item that needs to be bought for this discount to apply
    item_quantity_min = db.Column(db.Integer, default=1, nullable=False)
    percentage = db.Column(db.Integer, nullable=True)
    # price-based discount
    is_price_based = db.Column(db.Boolean, default=False, nullable=False)

    discount_code_base = db.Column(db.Unicode(20), nullable=True)
    secret = db.Column(db.Unicode(50), nullable=True)

    items = db.relationship('Item', secondary=item_discount_policy)
    # Coupons generated in bulk are not stored in the database during generation.
    # This field allows specifying the number of times a coupon, generated in bulk, can be used
    # This is particularly useful for generating referral discount coupons. For instance, one could generate
    # a signed coupon and provide it to a user such that the user can share the coupon `n` times
    # `n` here is essentially bulk_coupon_usage_limit.
    bulk_coupon_usage_limit = db.Column(db.Integer, nullable=True, default=1)

    def __init__(self, *args, **kwargs):
        self.secret = kwargs.get('secret') if kwargs.get('secret') else buid()
        super(DiscountPolicy, self).__init__(*args, **kwargs)

    @cached_property
    def is_automatic(self):
        return self.discount_type == DISCOUNT_TYPE.AUTOMATIC

    @cached_property
    def is_coupon(self):
        return self.discount_type == DISCOUNT_TYPE.COUPON

    def gen_signed_code(self, identifier=None):
        """Generates a signed code in the format discount_code_base.randint.signature"""
        if not identifier:
            identifier = buid()
        signer = Signer(self.secret)
        key = "{base}.{identifier}".format(base=self.discount_code_base, identifier=identifier)
        return signer.sign(key)

    @staticmethod
    def is_signed_code_format(code):
        """Checks if the code is in the {x.y.z} format"""
        return len(code.split('.')) == 3 if code else False

    @classmethod
    def get_from_signed_code(cls, code):
        """Returns a discount policy given a valid signed code, returns None otherwise"""
        if not cls.is_signed_code_format(code):
            return None
        discount_code_base = code.split('.')[0]
        policy = cls.query.filter_by(discount_code_base=discount_code_base).one_or_none()
        if not policy:
            return None
        signer = Signer(policy.secret)
        try:
            signer.unsign(code)
            return policy
        except BadSignature:
            return None

    @classmethod
    def make_bulk(cls, discount_code_base, **kwargs):
        """
        Returns a discount policy for the purpose of issuing signed discount coupons in bulk.
        """
        return cls(discount_type=DISCOUNT_TYPE.COUPON, discount_code_base=discount_code_base, secret=buid(), **kwargs)
Пример #2
0
from sqlalchemy import event, DDL
from baseframe import __
from coaster.utils import LabeledEnum, uuid1mc, buid
from boxoffice.models import db, IdMixin, BaseScopedNameMixin
from boxoffice.models import Organization

__all__ = ['DiscountPolicy', 'DiscountCoupon', 'item_discount_policy', 'DISCOUNT_TYPE']


class DISCOUNT_TYPE(LabeledEnum):
    AUTOMATIC = (0, __("Automatic"))
    COUPON = (1, __("Coupon"))


item_discount_policy = db.Table('item_discount_policy', db.Model.metadata,
    db.Column('item_id', None, db.ForeignKey('item.id'), primary_key=True),
    db.Column('discount_policy_id', None, db.ForeignKey('discount_policy.id'), primary_key=True),
    db.Column('created_at', db.DateTime, default=datetime.utcnow, nullable=False))


class DiscountPolicy(BaseScopedNameMixin, db.Model):
    """
    Consists of the discount rules applicable on items

    `title` has a GIN index to enable trigram matching.
    """
    __tablename__ = 'discount_policy'
    __uuid_primary_key__ = True
    __table_args__ = (db.UniqueConstraint('organization_id', 'name'),
        db.UniqueConstraint('organization_id', 'discount_code_base'),
        db.CheckConstraint('percentage > 0 and percentage <= 100', 'discount_policy_percentage_check'),
Пример #3
0
class Order(BaseMixin, db.Model):
    __tablename__ = 'customer_order'
    __uuid_primary_key__ = True
    __table_args__ = (db.UniqueConstraint('organization_id', 'invoice_no'),
        db.UniqueConstraint('access_token'))

    user_id = db.Column(None, db.ForeignKey('user.id'), nullable=True)
    user = db.relationship(User, backref=db.backref('orders', cascade='all, delete-orphan'))
    item_collection_id = db.Column(None, db.ForeignKey('item_collection.id'), nullable=False)
    item_collection = db.relationship('ItemCollection', backref=db.backref('orders', cascade='all, delete-orphan', lazy='dynamic'))

    organization_id = db.Column(None, db.ForeignKey('organization.id'), nullable=False)
    organization = db.relationship('Organization', backref=db.backref('orders', cascade='all, delete-orphan', lazy='dynamic'))

    status = db.Column(db.Integer, default=ORDER_STATUS.PURCHASE_ORDER, nullable=False)

    initiated_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    paid_at = db.Column(db.DateTime, nullable=True)
    invoiced_at = db.Column(db.DateTime, nullable=True)
    cancelled_at = db.Column(db.DateTime, nullable=True)

    access_token = db.Column(db.Unicode(22), nullable=False, default=buid)

    buyer_email = db.Column(db.Unicode(254), nullable=False)
    buyer_fullname = db.Column(db.Unicode(80), nullable=False)
    buyer_phone = db.Column(db.Unicode(16), nullable=False)

    # TODO: Deprecate invoice_no, rename to receipt_no instead
    invoice_no = db.Column(db.Integer, nullable=True)

    def permissions(self, user, inherited=None):
        perms = super(Order, self).permissions(user, inherited)
        if self.organization.userid in user.organizations_owned_ids():
            perms.add('org_admin')
        return perms

    def confirm_sale(self):
        """Updates the status to ORDER_STATUS.SALES_ORDER"""
        for line_item in self.line_items:
            line_item.confirm()
        self.invoice_no = gen_invoice_no(self.organization)
        self.status = ORDER_STATUS.SALES_ORDER
        self.paid_at = datetime.utcnow()

    def invoice(self):
        """Sets invoiced_at, status"""
        for line_item in self.line_items:
            line_item.confirm()
        self.invoiced_at = datetime.utcnow()
        self.status = ORDER_STATUS.INVOICE

    def get_amounts(self, line_item_status):
        """
        Calculates and returns the order's base_amount, discounted_amount,
        final_amount, confirmed_amount as a namedtuple for all the line items with the given status.
        """
        base_amount = Decimal(0)
        discounted_amount = Decimal(0)
        final_amount = Decimal(0)
        confirmed_amount = Decimal(0)
        for line_item in self.line_items:
            if line_item.status == line_item_status:
                base_amount += line_item.base_amount
                discounted_amount += line_item.discounted_amount
                final_amount += line_item.final_amount
            if line_item.is_confirmed:
                confirmed_amount += line_item.final_amount
        return order_amounts_ntuple(base_amount, discounted_amount, final_amount, confirmed_amount)

    @property
    def is_confirmed(self):
        return self.status in ORDER_STATUS.CONFIRMED

    def is_fully_assigned(self):
        """Checks if all the line items in an order have an assignee"""
        for line_item in self.get_confirmed_line_items:
            if not line_item.current_assignee:
                return False
        return True
Пример #4
0
class LineItem(BaseMixin, db.Model):
    """
    Note: Line Items MUST NOT be deleted.
    They must only be cancelled.

    # TODO: Rename this model to `Ticket`
    """
    __tablename__ = 'line_item'
    __uuid_primary_key__ = True
    __table_args__ = (db.UniqueConstraint('customer_order_id',
                                          'line_item_seq'),
                      db.UniqueConstraint('previous_id'))

    # line_item_seq is the relative number of the line item per order.
    line_item_seq = db.Column(db.Integer, nullable=False)
    customer_order_id = db.Column(None,
                                  db.ForeignKey('customer_order.id'),
                                  nullable=False,
                                  index=True,
                                  unique=False)
    order = db.relationship(Order,
                            backref=db.backref('line_items',
                                               cascade='all, delete-orphan',
                                               order_by=line_item_seq,
                                               collection_class=ordering_list(
                                                   'line_item_seq',
                                                   count_from=1)))

    item_id = db.Column(None,
                        db.ForeignKey('item.id'),
                        nullable=False,
                        index=True,
                        unique=False)
    item = db.relationship(Item,
                           backref=db.backref('line_items',
                                              cascade='all, delete-orphan'))

    previous_id = db.Column(None,
                            db.ForeignKey('line_item.id'),
                            nullable=True,
                            index=True,
                            unique=True)
    previous = db.relationship(
        'LineItem',
        primaryjoin='line_item.c.id==line_item.c.previous_id',
        backref=db.backref('revision', uselist=False),
        remote_side='LineItem.id')

    discount_policy_id = db.Column(None,
                                   db.ForeignKey('discount_policy.id'),
                                   nullable=True,
                                   index=True,
                                   unique=False)
    discount_policy = db.relationship('DiscountPolicy',
                                      backref=db.backref('line_items'))

    discount_coupon_id = db.Column(None,
                                   db.ForeignKey('discount_coupon.id'),
                                   nullable=True,
                                   index=True,
                                   unique=False)
    discount_coupon = db.relationship('DiscountCoupon',
                                      backref=db.backref('line_items'))

    base_amount = db.Column(db.Numeric, default=Decimal(0), nullable=False)
    discounted_amount = db.Column(db.Numeric,
                                  default=Decimal(0),
                                  nullable=False)
    final_amount = db.Column(db.Numeric, default=Decimal(0), nullable=False)
    status = db.Column(db.Integer,
                       default=LINE_ITEM_STATUS.PURCHASE_ORDER,
                       nullable=False)
    ordered_at = db.Column(db.DateTime, nullable=True)
    cancelled_at = db.Column(db.DateTime, nullable=True)

    def permissions(self, user, inherited=None):
        perms = super(LineItem, self).permissions(user, inherited)
        if self.order.organization.userid in user.organizations_owned_ids():
            perms.add('org_admin')
        return perms

    @classmethod
    def calculate(cls, line_items, recalculate=False, coupons=[]):
        """
        Returns line item tuples with the respective base_amount, discounted_amount,
        final_amount, discount_policy and discount coupon populated

        If the `recalculate` flag is set to `True`, the line_items will be considered as SQLAlchemy objects.
        """
        item_line_items = {}
        calculated_line_items = []
        coupon_list = list(set(coupons)) if coupons else []
        discounter = LineItemDiscounter()

        # make named tuples for line items,
        # assign the base_amount for each of them, None if an item is unavailable
        for line_item in line_items:
            if recalculate:
                item = line_item.item
                # existing line item, use the original base amount
                base_amount = line_item.base_amount
                line_item_id = line_item.id
            else:
                item = Item.query.get(line_item['item_id'])
                # new line item, use the current price
                base_amount = item.current_price(
                ).amount if item.is_available else None
                line_item_id = None

            if not item_line_items.get(unicode(item.id)):
                item_line_items[unicode(item.id)] = []
            item_line_items[unicode(item.id)].append(
                make_ntuple(item_id=item.id,
                            base_amount=base_amount,
                            line_item_id=line_item_id))

        for item_id in item_line_items.keys():
            calculated_line_items.extend(
                discounter.get_discounted_line_items(item_line_items[item_id],
                                                     coupon_list))

        return calculated_line_items

    def confirm(self):
        self.status = LINE_ITEM_STATUS.CONFIRMED

    # TODO: assignee = db.relationship(Assignee, primaryjoin=Assignee.line_item == self and Assignee.current == True, uselist=False)
    # Don't use current_assignee -- we want to imply that there can only be one assignee and the rest are historical (and hence not 'assignees')
    @property
    def current_assignee(self):
        return self.assignees.filter(Assignee.current == True).one_or_none()

    @property
    def is_confirmed(self):
        return self.status == LINE_ITEM_STATUS.CONFIRMED

    @property
    def is_cancelled(self):
        return self.status == LINE_ITEM_STATUS.CANCELLED

    @property
    def is_free(self):
        return self.final_amount == Decimal('0')

    def cancel(self):
        """Sets status and cancelled_at."""
        self.status = LINE_ITEM_STATUS.CANCELLED
        self.cancelled_at = func.utcnow()

    def make_void(self):
        self.status = LINE_ITEM_STATUS.VOID
        self.cancelled_at = func.utcnow()

    def is_cancellable(self):
        return self.is_confirmed and (
            datetime.datetime.utcnow() < self.item.cancellable_until
            if self.item.cancellable_until else True)

    @classmethod
    def get_max_seq(cls, order):
        return db.session.query(func.max(
            LineItem.line_item_seq)).filter(LineItem.order == order).scalar()
Пример #5
0
class Order(BaseMixin, db.Model):
    __tablename__ = 'customer_order'
    __uuid_primary_key__ = True
    __table_args__ = (db.UniqueConstraint('organization_id', 'invoice_no'),
                      db.UniqueConstraint('access_token'))

    user_id = db.Column(None, db.ForeignKey('user.id'), nullable=True)
    user = db.relationship(User,
                           backref=db.backref('orders',
                                              cascade='all, delete-orphan'))
    item_collection_id = db.Column(None,
                                   db.ForeignKey('item_collection.id'),
                                   nullable=False)
    item_collection = db.relationship('ItemCollection',
                                      backref=db.backref(
                                          'orders',
                                          cascade='all, delete-orphan',
                                          lazy='dynamic'))

    organization_id = db.Column(None,
                                db.ForeignKey('organization.id'),
                                nullable=False)
    organization = db.relationship('Organization',
                                   backref=db.backref(
                                       'orders',
                                       cascade='all, delete-orphan',
                                       lazy='dynamic'))

    status = db.Column(db.Integer,
                       default=ORDER_STATUS.PURCHASE_ORDER,
                       nullable=False)

    initiated_at = db.Column(db.DateTime,
                             nullable=False,
                             default=datetime.utcnow)
    paid_at = db.Column(db.DateTime, nullable=True)
    invoiced_at = db.Column(db.DateTime, nullable=True)
    cancelled_at = db.Column(db.DateTime, nullable=True)

    access_token = db.Column(db.Unicode(22), nullable=False, default=buid)

    buyer_email = db.Column(db.Unicode(254), nullable=False)
    buyer_fullname = db.Column(db.Unicode(80), nullable=False)
    buyer_phone = db.Column(db.Unicode(16), nullable=False)

    invoice_no = db.Column(db.Integer, nullable=True)

    def confirm_sale(self):
        """Updates the status to ORDER_STATUS.SALES_ORDER"""
        for line_item in self.line_items:
            line_item.confirm()
        self.invoice_no = get_latest_invoice_no(self.organization) + 1
        self.status = ORDER_STATUS.SALES_ORDER
        self.paid_at = datetime.utcnow()

    def invoice(self):
        """Sets invoiced_at, status"""
        for line_item in self.line_items:
            line_item.confirm()
        self.invoiced_at = datetime.utcnow()
        self.status = ORDER_STATUS.INVOICE

    def get_amounts(self):
        """
        Calculates and returns the order's base_amount, discounted_amount and
        final_amount as a namedtuple
        """
        base_amount = Decimal(0)
        discounted_amount = Decimal(0)
        final_amount = Decimal(0)
        for line_item in self.line_items:
            base_amount += line_item.base_amount
            discounted_amount += line_item.discounted_amount
            final_amount += line_item.final_amount
        return order_amounts_ntuple(base_amount, discounted_amount,
                                    final_amount)