예제 #1
0
 def find_all_by_code(code, db=None):
     if not db:
         db = CouponsAlchemyDB()
     voucher_list = list()
     voucher_dict_list = db.find("all_vouchers", **{'code': code})
     for voucher_dict in voucher_dict_list:
         voucher = Vouchers.from_dict(voucher_dict)
         voucher_list.append(voucher)
     return voucher_list
예제 #2
0
def apply_benefits(args, order, benefits):
    order_id = args.get('order_id')
    user_id = args.get('customer_id')
    voucher_id_list = list()
    db = CouponsAlchemyDB()
    db.begin()
    try:
        rows_with_order_id = db.find("voucher_use_tracker",
                                     **{'order_id': order_id})
        if rows_with_order_id:
            db.delete_row_in_transaction("voucher_use_tracker",
                                         **{'order_id': order_id})
        for existing_voucher in order.existing_vouchers:
            voucher_id = existing_voucher['voucher'].id
            if voucher_id in voucher_id_list:
                continue
            voucher_id_list.append(voucher_id)
            rule = existing_voucher['voucher'].rules_list[0]
            if hasattr(order, 'validate') and not order.validate:
                pass
            else:
                success, error = rule.criteria_obj.check_usage(
                    order.customer_id, existing_voucher['voucher'].id_bin,
                    order_id, db)
                if not success:
                    db.rollback()
                    return False, 400, default_error_message

            if config.client == 'new_grocery':
                customer_id = getattr(request, "phone_no", "-")
            else:
                customer_id = user_id

            session_id = request.headers.get('X-ASKME-SESSIONID', None)
            user_uuid = request.headers.get('X-ASKME-USERID', None)

            transaction_log = VoucherTransactionLog(
                **{
                    'id': uuid.uuid1().hex,
                    'user_id': customer_id,
                    'session_id': session_id,
                    'user_uuid': user_uuid,
                    'voucher_id': voucher_id,
                    'order_id': order_id,
                    'status': VoucherTransactionStatus.in_progress.value,
                    'response': json.dumps(benefits)
                })
            transaction_log.save(db)
        db.commit()
    except Exception as e:
        logger.exception(e)
        db.rollback()
        return False, 500, u'Unknown Error. Please try after some time'
    # else:
    #     db.commit()
    return True, 200, None
예제 #3
0
def cleanup_rules():
    rule_criteria_class = getattr(
            importlib.import_module(
                method_dict.get('criteria_class')['package']),
            method_dict.get('criteria_class')['attribute'])
    db = CouponsAlchemyDB()
    rule_dict_list = db.find("rule")
    for rule_dict in rule_dict_list:
        rule_dict['id'] = binascii.b2a_hex(rule_dict['id'])
        rule = Rule(**rule_dict)
        criteria_dict = canonicaljson.json.loads(rule.criteria_json)
        if rule.blacklist_criteria_json:
            blacklist_dict = canonicaljson.json.loads(rule.blacklist_criteria_json)
        else:
            blacklist_dict = dict()

        all_list = ['all']

        criteria_payment_modes = criteria_dict.get('payment_modes')
        if criteria_payment_modes:
            criteria_payment_modes = [criteria_payment_mode.lower() for criteria_payment_mode in criteria_payment_modes]

        if criteria_payment_modes and get_intersection_of_lists(criteria_payment_modes, all_list):
            del criteria_dict['payment_modes']

        blacklist_criteria_payment_modes = blacklist_dict.get('payment_modes')
        if blacklist_criteria_payment_modes:
            blacklist_criteria_payment_modes = [blacklist_criteria_payment_mode.lower() for blacklist_criteria_payment_mode in blacklist_criteria_payment_modes]

        if blacklist_criteria_payment_modes and get_intersection_of_lists(blacklist_criteria_payment_modes, all_list):
            del blacklist_dict['payment_modes']
        try:
            criteria_dict['valid_on_order_no'] = fix_order_no(criteria_dict.get('valid_on_order_no'))
        except ValueError:
            success = False
            # error.append(u'Invalid value in valid_on_order_no in rule criteria')

        try:
            blacklist_dict['valid_on_order_no'] = fix_order_no(blacklist_dict.get('valid_on_order_no'))
        except ValueError:
            success = False
            # error.append(u'Invalid value in valid_on_order_no in rule blacklist criteria')
        benefit_dict = canonicaljson.json.loads(rule.benefits_json)
        rule_criteria = rule_criteria_class(**criteria_dict)
        rule_blacklist_criteria = rule_criteria_class(**blacklist_dict)
        benefits = Benefits(**benefit_dict)
        values = dict()
        values['id'] = rule.id_bin
        values['criteria_json'] = rule_criteria.canonical_json()
        values['blacklist_criteria_json'] = rule_blacklist_criteria.canonical_json()
        values['benefits_json'] = benefits.canonical_json()
        un_hashed_string = unicode(values['criteria_json']) + \
            unicode(values['criteria_json']) + unicode(values['criteria_json'])
        values['sha2hash'] = hashlib.sha256(un_hashed_string).hexdigest()
        db.update_row("rule", "id", **values)
예제 #4
0
def fetch_order_response(args):
    order_id = args.get('order_id')
    user_id = args.get('customer_id')
    db = CouponsAlchemyDB()
    result = db.find("voucher_use_tracker", **{
        'order_id': order_id,
        'user_id': user_id
    })
    if result:
        # result may have one entry per voucher,
        # but all entries will have same json for an order id,
        # Hence its safe accessing the list's 0th element
        return True, json.loads(result[0]['response'])
    return False, None
예제 #5
0
    def make_transaction_log_entry(args):
        db = CouponsAlchemyDB()
        db.begin()
        success = True
        error = None
        try:
            voucher_use_list_of_dict = db.find(
                "user_voucher_transaction_log",
                order_by="_updated_on",
                **{'order_id': args.get('order_id')})
            if not voucher_use_list_of_dict:
                success = False
                error = u'No Order found for the given order id'
            else:
                last_log = VoucherTransactionLog.dict_to_obj(
                    voucher_use_list_of_dict[0])
                if args.get('payment_status'):
                    status = VoucherTransactionStatus.success.value
                else:
                    status = VoucherTransactionStatus.failure.value
                id = uuid.uuid1().hex
                log = VoucherTransactionLog(
                    **{
                        'id': id,
                        'user_id': last_log.user_id,
                        'voucher_id': last_log.voucher_id,
                        'order_id': last_log.order_id,
                        'status': status
                    })
                log.save(db)
                success = True
                error = None
            db.commit()
        except Exception as e:
            logger.exception(e)
            db.rollback()
            success = False
            error = u'Unknown error'

        return success, error
예제 #6
0
 def save(self):
     values = self.get_value_dict()
     db = CouponsAlchemyDB()
     db.begin()
     # update_cache = False
     try:
         # check if the rule being created already exists, if yes, just return rule id
         existing_rule = db.find_one("rule", **{'id': self.id_bin})
         if existing_rule:
             # call is to update the existing rule with new attributes, just update and save it
             # update_cache = True
             logger.error('Trying to update an existing rule {}'.format(
                 self.__dict__))
             assert False, "A Rule is immutable."
         # no existing rule exists for this id, now check if a rule exists for given attributes
         rule_list = db.find("rule", **{'sha2hash': values.get('sha2hash')})
         if rule_list:
             for rule in rule_list:
                 rule['id'] = binascii.b2a_hex(rule['id'])
                 rule_obj = Rule(**rule)
                 if self == rule_obj:
                     self.id = rule_obj.id
                     break
         else:
             # update_cache = True
             db.insert_row("rule", **values)
         db.commit()
     except Exception as e:
         logger.exception(e)
         db.rollback()
         return False
     # else:
     #     db.commit()
     # if update_cache:
     #     self.update_cache()
     return self.id
예제 #7
0
def generate_auto_freebie():
    db = CouponsAlchemyDB()
    db.delete_row("auto_benefits")
    voucher_list = db.find("vouchers")
    for voucher in voucher_list:
        save_auto_freebie_from_voucher_dict(voucher)