Пример #1
0
 def save(self):
     values = self.get_value_dict()
     db = CouponsAlchemyDB()
     db.begin()
     try:
         from src.rules.utils import is_validity_period_exclusive_for_voucher_code
         success, error = is_validity_period_exclusive_for_voucher_code(
             self, db)
         if not success:
             db.rollback()
             return False, None, error
         db.insert_row("all_vouchers", **values)
         Vouchers.fetch_active_voucher(self.code, db)
         db.commit()
     except sqlalchemy.exc.IntegrityError as e:
         db.rollback()
         # should not happen
         return False, None, u'Voucher code already exists'
     except Exception as e:
         logger.exception(e)
         db.rollback()
         return False, None, u'Unknown Error'
     # else:
     #     db.commit()
     return True, {'id': self.id, 'code': self.code}, None
Пример #2
0
def save_auto_freebie_from_voucher(voucher, db=None):
    voucher.get_rule(db)
    if voucher.type is not VoucherType.regular_coupon.value:
        auto_freebie_values = dict()
        auto_freebie_values['type'] = voucher.type
        auto_freebie_values['zone'] = voucher.rules_list[0].criteria_obj.zone[
            0],
        auto_freebie_values['range_min'] = voucher.rules_list[
            0].criteria_obj.range_min
        auto_freebie_values['range_max'] = voucher.rules_list[
            0].criteria_obj.range_max
        auto_freebie_values['cart_range_min'] = voucher.rules_list[
            0].criteria_obj.cart_range_min
        auto_freebie_values['cart_range_max'] = voucher.rules_list[
            0].criteria_obj.cart_range_max
        auto_freebie_values['voucher_id'] = binascii.a2b_hex(voucher.id)
        if voucher.type is VoucherType.auto_freebie.value:
            auto_freebie_values['variants'] = voucher.rules_list[
                0].criteria_obj.variants[0]
        else:
            auto_freebie_values['variants'] = None
        auto_freebie_values['from'] = voucher.from_date
        auto_freebie_values['to'] = voucher.to_date
        if not db:
            db = CouponsAlchemyDB()
        db.insert_row("auto_benefits", **auto_freebie_values)
Пример #3
0
def update_keys_in_input_list(data_list):
    db = CouponsAlchemyDB()
    db.begin()
    change_id = None
    try:
        db.insert_row("all_vouchers_log_sequence")
        query = 'select last_insert_id() as id'
        max_change_log = db.execute_raw_sql(query, dict())
        change_id = max_change_log[0]['id']
        db.commit()
    except Exception as e:
        logger.exception(e)
        db.rollback()
        change_id = None
    success_list = list()
    error_list = list()
    if change_id:
        for data in data_list:
            success_list_in_this_data, error_list_in_this_data = update_values_in_this_list_of_coupons(
                data, change_id=change_id)
            success_list += success_list_in_this_data
            error_list += error_list_in_this_data
    return success_list, error_list
Пример #4
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
Пример #5
0
def replay_test(group_no):
    try:
        client = KafkaClient(hosts=KAFKAHOST)
    except Exception as e:
        return
    group_id = TEST_TOPIC_KAFKA + u'{}'.format(group_no)
    try:
        topic = client.topics[TEST_TOPIC_KAFKA]
        balanced_consumer = topic.get_balanced_consumer(
            consumer_group=str(group_id),
            auto_commit_enable=True,
            reset_offset_on_start=True,
            auto_offset_reset=common.OffsetType.LATEST,
            use_rdkafka=False,
            zookeeper_connect=ZOOKEEPER)
        for message in balanced_consumer:
            if message is not None:
                data = json.loads(message.value)
                end_point = data['url']
                body = data['body']
                if end_point.endswith(('check', 'apply')):
                    body_data = json.loads(body)
                    for product in body_data.get('products', list()):
                        product['subscription_id'] = product.get('item_id')
                    body = json.dumps(body_data)
                params = data['query']
                response = data['response']
                url = HOST + end_point
                headers = {
                    'X-API-USER': TEST_USER,
                    'X-API-TOKEN': TEST_TOKEN,
                    'Content-Type': 'Application/Json'
                }

                response_on_staging_obj = make_api_call(url=url,
                                                        body=json.loads(body),
                                                        method='POST',
                                                        headers=headers,
                                                        params=params)
                response_on_staging = response_on_staging_obj.text

                data = {
                    'url': end_point,
                    'body': body,
                    'params': json.dumps(params),
                    'prod_response': response,
                    'staging_response': response_on_staging,
                    'body_varchar': body,
                    'prod_response_varchar': response,
                    'staging_response_varchar': response_on_staging,
                    'match': response_on_staging == response
                }

                db = CouponsAlchemyDB()
                db.begin()
                try:
                    try:
                        db.insert_row("auto_tester", **data)
                    except DataError:
                        del data['body_varchar']
                        del data['prod_response_varchar']
                        del data['staging_response_varchar']
                        db.insert_row("auto_tester", **data)
                    db.commit()
                except Exception as e:
                    logger.exception(e)
                    db.rollback()
    except Exception as e:
        logger.exception(e)
Пример #6
0
def create_freebie_coupon(args):
    # code must have only 1 element and it has been validated before
    # hence safe in accessing directly 0th element
    # in case of update, delete the voucher, delete entry from auto_benefits
    # create a new rule and create a new voucher on the created rule, and an entry in auto_benefits
    # Also it is ensured that at a time only one entry per zone, spending range and category can be there.
    # Currently Scheduling is not supported in Freebies

    if args.get('schedule'):
        return False, None, [u'Scheduling is not supported in Freebie Coupons']

    code = args.get('code')[0]
    rule = args.get('rules')[0]
    criteria = rule.get('criteria')
    existing_voucher_dict = {
        'type': args.get('type'),
        'zone': criteria.get('location').get('zone')[0],
        'range_min': criteria.get('range_min'),
        'range_max': criteria.get('range_max'),
        'cart_range_min': criteria.get('cart_range_min'),
        'cart_range_max': criteria.get('cart_range_max'),
        'from': args.get('from'),
        'to': args.get('to'),
        'code': code
    }
    data = {
        'criteria': {
            'categories': {
                'in': [],
                'not_in': []
            },
            'no_of_uses_allowed_per_user':
            criteria.get('no_of_uses_allowed_per_user'),
            'no_of_total_uses_allowed':
            criteria.get('no_of_total_uses_allowed'),
            'valid_on_order_no':
            criteria.get('valid_on_order_no'),
            'location': {
                'country': [],
                'state': [],
                'area': [],
                'city': [],
                'zone': criteria.get('location').get('zone')
            },
            'range_min':
            criteria.get('range_min'),
            'range_max':
            criteria.get('range_max'),
            'cart_range_min':
            criteria.get('cart_range_min'),
            'cart_range_max':
            criteria.get('cart_range_max'),
            'channels': [],
            'brands': [],
            'products': {
                'in': [],
                'not_in': []
            },
            'storefronts': [],
            'sellers': [],
            'payment_modes': []
        },
        'benefits': [{
            'type': 2,
            'freebies': rule.get('benefits')[0].get('freebies'),
        }],
        'description':
        rule.get('description')
    }
    if args.get('type') is VoucherType.auto_freebie.value:
        existing_voucher_dict['variants'] = criteria.get('variants')[0]
        data['criteria']['variants'] = criteria.get('variants')
    else:
        existing_voucher_dict['variants'] = None
        data['criteria']['variants'] = []

    success, error_list = is_validity_period_exclusive_for_freebie_voucher_code(
        existing_voucher_dict)
    if not success:
        return False, None, error_list

    rule_obj = create_rule_object(data, args.get('user_id'),
                                  get_criteria_kwargs)
    rule_obj.save()
    success_list, error_list = save_vouchers(args, [rule_obj.id])
    if not error_list:
        voucher_id = success_list[0]['id']
        auto_freebie_values = dict()
        auto_freebie_values['type'] = args.get('type')
        auto_freebie_values['zone'] = criteria.get('location').get('zone')[0],
        auto_freebie_values['range_min'] = criteria.get('range_min')
        auto_freebie_values['range_max'] = criteria.get('range_max')
        auto_freebie_values['cart_range_min'] = criteria.get('cart_range_min')
        auto_freebie_values['cart_range_max'] = criteria.get('cart_range_max')
        auto_freebie_values['voucher_id'] = binascii.a2b_hex(voucher_id)
        auto_freebie_values['variants'] = existing_voucher_dict['variants']
        auto_freebie_values['from'] = args.get('from')
        auto_freebie_values['to'] = args.get('to')
        db = CouponsAlchemyDB()
        db.insert_row("auto_benefits", **auto_freebie_values)

    for s in success_list:
        del s['id']
    return True, success_list, error_list