예제 #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 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 fetch_active_voucher(code, db=None):
     if not db:
         db = CouponsAlchemyDB()
         db.begin()
         try:
             active_voucher = Vouchers.get_active_voucher(code, db)
             db.commit()
             return active_voucher
         except Exception as e:
             logger.exception(e)
             db.rollback()
             return False
     else:
         return Vouchers.get_active_voucher(code, db)
예제 #4
0
def update_coupon(coupon, update_dict, change_id):
    db = CouponsAlchemyDB()
    db.begin()
    try:
        success, voucher, error = fetch_voucher_for_coupon_details(coupon, db)
        if not success:
            db.rollback()
            return False, error
        success, error_list = voucher.update(update_dict, db, change_id)
        if not success:
            db.rollback()
            return False, u','.join(error_list)
        db.commit()
    except Exception as e:
        logger.exception(e)
        db.rollback()
        return False, u'Unknown Error. Please Contact tech support'
    return True, None
예제 #5
0
 def save(self, db=None):
     values = self.get_value_dict_for_log()
     if not db:
         db = CouponsAlchemyDB()
         db.begin()
         try:
             function = self.save_function().get(self.status_enum)
             function(db, values)
             db.commit()
         except Exception as e:
             logger.exception(e)
             db.rollback()
             return False
         # else:
         #     db.commit()
         return True
     else:
         function = self.save_function().get(self.status_enum)
         function(db, values)
예제 #6
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
예제 #7
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
예제 #8
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
예제 #9
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)