Ejemplo n.º 1
0
def test_get_verification_code():
    """
    获取手机验证码
    :return:
    """
    now = datetime.now()
    res = ResMsg()

    category = request.args.get("category", None)
    # category 参数如下:
    # authentication: 身份验证
    # login_confirmation: 登陆验证
    # login_exception: 登陆异常
    # user_registration: 用户注册
    # change_password: 修改密码
    # information_change: 信息修改

    phone = request.args.get('phone', None)

    # 验证手机号码正确性
    re_phone = PhoneTool.check_phone(phone)
    if phone is None or re_phone is None:
        res.update(code=ResponseCode.MobileNumberError)
        return res.data
    if category is None:
        res.update(code=ResponseCode.InvalidParameter)
        return res.data

    try:
        # 获取手机验证码设置时间
        flag = Redis.hget(re_phone, 'expire_time')
        if flag is not None:
            flag = datetime.strptime(flag, '%Y-%m-%d %H:%M:%S')
            # 判断是否重复操作
            if (flag - now).total_seconds() < 60:
                res.update(code=ResponseCode.FrequentOperation)
                return res.data

        # 获取随机验证码
        code = "".join([str(random.randint(0, 9)) for _ in range(6)])
        template_param = {"code": code}
        # 发送验证码
        sms = SendSms(phone=re_phone,
                      category=category,
                      template_param=template_param)
        sms.send_sms()
        # 将验证码存入redis,方便接下来的验证
        Redis.hset(re_phone, "code", code)
        # 设置重复操作屏障
        Redis.hset(re_phone, "expire_time",
                   (now + timedelta(minutes=1)).strftime('%Y-%m-%d %H:%M:%S'))
        # 设置验证码过去时间
        Redis.expire(re_phone, 60 * 3)
        return res.data
    except Exception as e:
        logger.exception(e)
        res.update(code=ResponseCode.Fail)
        return res.data
Ejemplo n.º 2
0
def new_member_reward(from_user: int = 1):
    # 拉新邀请奖励
    from_user_id = from_user

    is_new_member = Redis.hget(is_new_member_key, from_user_id)

    if is_new_member:

        logger.info('parentid: is_new_member:' + is_new_member)
        parent_id = is_new_member
        is_sendbalance_redis = is_sendbalance_key + str(parent_id)

        is_send_balance = Redis.sismember(is_sendbalance_redis, from_user_id)

        # not in the set that means the mid not send balance to the parent_id
        if not is_send_balance:

            user = db.session.query(EtMember).filter(
                EtMember.id == parent_id).first()

            logger.info(f'{is_sendbalance_redis}:' + str(is_send_balance))

            drp_send = db.session.query(EtMemberDrp).filter(
                EtMemberDrp.member_id == parent_id,
                EtMemberDrp.from_task_id == 9999_9999,
                EtMemberDrp.from_member_id == from_user_id).first()
            logger.info(drp_send)
            if not drp_send:
                # from_task_id give a max value
                # add drp records
                drp_earning_dict = {
                    "member_id": parent_id,
                    "from_task_id": 9999_9999,
                    "amounts": 1,
                    "from_member_id": from_user_id,
                }
                new_drp_earning = EtMemberDrp(**drp_earning_dict)
                db.session.add(new_drp_earning)

                update_dict = {
                    "balance": 100 + user.balance,
                    "balance_version": int(time.time())
                }

                # update member balance
                db.session.query(EtMember).filter(
                    EtMember.id == user.id, EtMember.balance_version ==
                    user.balance_version).update(update_dict)
            try:
                db.session.commit()

                # update user cache
                Redis.delete(user_center_key + str(user.id))
                Redis.delete(user_info_key + str(user.mobile))
                Redis.delete(user_task_earnings_key + str(user.id))
                Redis.delete(user_appretice_detail_key + str(user.id))
                Redis.delete(user_apprentice_key + str(user.id))

                # update set of the send mids under the parentid
                Redis.sadd(is_sendbalance_redis, from_user_id)

                logger.info(f'from {from_user_id} to {parent_id} 发放邀请奖励成功')

            except Exception as why:

                logger.info(str(why))
Ejemplo n.º 3
0
def calculating_earnings(task_order:dict, task_id:int, type_set:int =1):
    '''
    计算该用户收益 同时异步完成该用户 所有上级 收益更新
    #type_set 收益来源:1:任务收益 2:分销佣金3:新手红包奖励
    '''
    res = ResMsg()
    if isinstance(task_order, dict):
        task = db.session.query(EtTask).filter(EtTask.id == task_id).first()
        logger.info('发放父亲节点收益')
        if task:
            task_dict= dict(helpers.model_to_dict(task))
            logger.info(task_dict)

            if task_dict['task_class']==3:
                type_set = 3
            

            task_earning_money= float(task_dict['task_reward'])
            
            earning_dict ={
                "member_id": task_order['member_id'],
                "task_id": task_id,
                "amounts": task_earning_money,
                "task_order_id": task_order['id'],
                "amount_type": type_set
            }
            logger.info(earning_dict)
            new_earning = EtMemberEarning(**earning_dict)

            isearn_sended= user = db.session.query(EtMemberEarning).filter(
                EtMemberEarning.task_order_id == task_order['id']).first()

            if isearn_sended:
                logger.info("该用户订单收益已发放")
                return "该用户订单收益已发放'"

            db.session.add(new_earning)

            user = db.session.query(EtMember).filter(
                EtMember.id == task_order['member_id']).first()

            if user.status==2:
                res.update(dict(code=ResponseCode.Success, data={},
                                msg=f'该用户已禁用,无法获得收益'))
                return res
                
            if user:
                try:
                    update_dict = {
                        "balance": task_earning_money*100 + user.balance,
                        "balance_version": int(time.time())
                    }

                    db.session.query(EtMember).filter(
                        EtMember.id == task_order['member_id'], EtMember.balance_version == user.balance_version).update(update_dict)
                    db.session.commit()

                    # update user cache
                    Redis.delete(user_center_key + str(user.id))
                    Redis.delete(user_info_key + str(user.mobile))
                    Redis.delete(user_task_earnings_key + str(user.id))

                    #缓存获取分销比例参数
                    drp_config = Redis.hgetall(redis_key_drp)
                    per_sets = json.loads(drp_config[b'profit_percentage'].decode('utf8'))
                    
                    logger.info(per_sets)
                    
                    # get各级分销比例
                    profit_percentage_arr=[]
                    for i in range(len(per_sets)):
                        profit_percentage_arr.append (per_sets[i]['per'])
                    
                    logger.info("比例设置:")
                    # logger.info(profit_percentage_arr) 
                    
                    # get当前用户关系树
                    rel_from_relations = db.session.execute(f"SELECT * FROM et_member_relations WHERE member_id={task_order['member_id']}").first()
                    root_id= None

                    if rel_from_relations['parent_id']:
                        root_id= rel_from_relations['parent_id']

                    if rel_from_relations['top_parent_id']:
                        root_id= rel_from_relations['top_parent_id']

                    realtion_tree_key_m = realtion_tree_key + str(root_id)
                    logger.info("tree:")
                    
                    tree_node = Redis.hget(realtion_tree_key_m, 0)
                    logger.info(str(tree_node))
                    realtion_tree_fromuser = json.loads(tree_node)

                    logger.info(str(realtion_tree_fromuser))
                    importer = DictImporter()
                    
                    parents=[]
                    realtion_tree = importer.import_(realtion_tree_fromuser)
                    cur_node_tuple  = realtionlib.findall_by_attr(realtion_tree, task_order['member_id'])
                    cur_node = cur_node_tuple[0]
                    logger.info('ancestors:')
                    logger.info(str(cur_node.ancestors)) 
                    
                    if cur_node.ancestors:
                        # async-task: for all parents : drp_earnings
                        for i,k in enumerate(cur_node.ancestors):
                            parents.append(k.name)
                            parentid= k.name
                            drp_level = i+1
                            logger.info('k-name:'+str(k.name))
                            logger.info('drp_level:'+str(drp_level))
                            if drp_level<4:
                                result = async_calculating_earnings.delay(parentid, drp_level, earning_dict, task_id, task_order['id'], type_set=2 )
                    
                        logger.info(parents) 

                    res.update(code=ResponseCode.Success, data={},msg=f'用户交单任务收益更新成功')
                    logger.info(res.data)
                except Exception as why:

                    res.update(code=ResponseCode.Success, data={},msg=f'用户交单任务收益数据添加失败{why}')
                    logger.info(res.data)
            else:
                res.update(code=ResponseCode.Success, data={},msg=f'用户信息异常{user}')