예제 #1
0
async def do_review(
        schema_in: ReviewResult,
        current_user: MarketAdminUser = Depends(require_super_scope_admin),
):
    """审核结果:通过 / 拒绝"""
    review = await ReviewRecord.get_or_404(schema_in.id)
    if review.review_status != int(ReviewStatus.wait):
        return CommonOut(errCode=-2, errMsg="操作失败,已完成审核")

    if review.product_type == int(ProductType.qstrategy):
        product = await QStrategy.get(review.product_id)
    elif review.product_type == int(ProductType.package):
        product = await StrategyPackage.get(review.product_id)
    if not product:
        return CommonOut(errCode=-2, errMsg="操作失败,没找到对应的策略 / 套餐")

    if product.status not in (int(ListStatus.online_review),
                              int(ListStatus.offline_review)):
        return CommonOut(errCode=-2, errMsg="操作失败,策略 / 套餐已完成审核")

    if schema_in.accept:
        review = review.update(review_status=int(ReviewStatus.accepted))
        if review.operation == int(ReviewOP.online):
            product = product.update(status=int(ListStatus.online))
        else:
            product = product.update(status=int(ListStatus.offline))
    else:
        review = review.update(review_status=int(ReviewStatus.rejected))
        if review.operation == int(ReviewOP.online):
            product = product.update(status=int(ListStatus.online_rejected))
        else:
            product = product.update(status=int(ListStatus.offline_rejected))
    await review.update(review_msg=schema_in.msg).apply()
    await product.apply()
    return CommonOut()
예제 #2
0
async def change_admin_status(
        schema_in: AdminUserChangeStatusIn,
        current_user: MarketAdminUser = Depends(require_super_scope_su),
):
    """禁用管理员"""
    if current_user.scope1 != "aq" or current_user.scope2 != int(
            UserScope2.su):
        return CommonOut(errCode=-100, errMsg="添加失败,没有权限")
    #try:
    #
    #    #await MarketAdminUser.update(status=int(schema_in.status)).where(
    #    #    MarketAdminUser.id == schema_in.id
    #    #)
    #    user = await MarketAdminUser.query.where(MarketAdminUser.id == schema_in.id).gino.first()
    #    await user.update(status=int(schema_in.status)).apply()
    #except Exception:
    #    logger.exception("更新管理员信息失败:%s", schema_in.json())
    #    return CommonOut(errCode=-1, errMsg="更新失败,请检查名字是否重复")
    if schema_in.status == UserStatus.deleted:
        user1 = await MarketAdminUser.query.where(
            MarketAdminUser.id == schema_in.id).gino.first()
        await user1.delete()
    else:
        try:
            user = await MarketAdminUser.query.where(
                MarketAdminUser.id == schema_in.id).gino.first()
            await user.update(status=int(schema_in.status)).apply()
        except Exception:
            logger.exception("更新管理员信息失败:%s", schema_in.json())
            return CommonOut(errCode=-1, errMsg="更新失败,请检查名字是否重复")
    return CommonOut()
예제 #3
0
async def edit_strategy(product_id: str, changed: QStrategyUpdateFields):
    """编辑上架策略"""
    try:
        await QStrategy.filter(product_id=product_id).update(**changed.dict())
    except Exception:
        logger.exception("更新策略 (%s) 失败:%s", product_id, changed.json())
        return CommonOut(errCode=-1, errMsg="更新失败,请检查名字是否重复")
    return CommonOut()
예제 #4
0
파일: strategy.py 프로젝트: 1445592270/game
async def check_buyed(task_id: str, request: Request):
    """检查是否需要因此策略信息"""
    try:
        if await check_task_permission(TaskType.PAPER_TRADING, task_id, request):
            return CommonOut()
    except Exception:
        pass
    return CommonOut(errCode=-1, errMsg="没有权限")
예제 #5
0
async def edit_strategy(product_id: str, changed: QStrategyUpdateFields):
    """编辑上架策略"""
    try:
        await QStrategy.update.values(**changed.dict()).where(
            QStrategy.product_id == product_id).gino.status()
    except Exception:
        logger.exception("更新策略 (%s) 失败:%s", product_id, changed.json())
        return CommonOut(errCode=-1, errMsg="更新失败,请检查名字是否重复")
    return CommonOut()
예제 #6
0
async def edit_admin(
        schema_in: AdminUserUpdate,
        current_user: MarketAdminUser = Depends(require_active_admin),
):
    """编辑管理员信息"""
    try:
        await MarketAdminUser.filter(id=schema_in.id
                                     ).update(**schema_in.changed.dict())
    except Exception:
        logger.exception("更新管理员信息失败:%s", schema_in.json())
        return CommonOut(errCode=-1, errMsg="更新失败,请检查名字是否重复")
    return CommonOut()
예제 #7
0
async def change_admin_status(
        schema_in: AdminUserChangeStatusIn,
        current_user: MarketAdminUser = Depends(require_super_scope_su),
):
    """禁用管理员"""
    if current_user.scope1 != "aq" or current_user.scope2 != UserScope2.su:
        return CommonOut(errCode=-100, errMsg="添加失败,没有权限")
    try:
        await MarketAdminUser.filter(id=schema_in.id
                                     ).update(status=schema_in.status)
    except Exception:
        logger.exception("更新管理员信息失败:%s", schema_in.json())
        return CommonOut(errCode=-1, errMsg="更新失败,请检查名字是否重复")
    return CommonOut()
예제 #8
0
async def add_package(
        schema_in: PkgCreate,
        current_user: MarketAdminUser = Depends(require_super_scope_admin),
):
    """添加套餐"""
    schema_in.product_id = uuid.uuid1()
    try:
        await StrategyPackage.create(**schema_in.dict())
    except IntegrityError:
        return CommonOut(errCode=-1, errMsg="添加失败,请检查名字是否重复")
    except Exception:
        logger.exception("create package failed: %s", schema_in.json())
        return CommonOut(errCode=-1, errMsg="添加失败,请检查名字是否重复")

    return CommonOut()
예제 #9
0
async def change_strategy_status(id_list: Union[str, List[str]],
                                 status: ListStatus):
    """直接重新上架策略"""
    if isinstance(id_list, str):
        id_list = [id_list]
    await QStrategy.filter(product_id__in=id_list).update(status=status)
    return CommonOut()
예제 #10
0
async def open_push(
        schema_in: PushCreate,
        request: Request,
        current_user: MarketUser = Depends(require_active_user),
):
    """开启推送"""
    if schema_in.push_method != PushMethod.wechat:
        raise HTTPException(status.HTTP_400_BAD_REQUEST, "push_id is needed")
    try:
        strategy = await QStrategy.get_or_none(
            product_id=schema_in.qstrategy_id)
    except DoesNotExist:
        raise HTTPException(status.HTTP_404_NOT_FOUND, "没找到对应策略")

    if await check_task_permission(TaskType.PAPER_TRADING, strategy.task_id,
                                   request):
        raise HTTPException(status.HTTP_401_UNAUTHORIZED, "没有权限")

    push_id = schema_in.push_id
    # TODO: check wechat bind for wechat push, check push_id for other method
    push = PushInfo(
        qstrategy_id=strategy.product_id,
        task_id=strategy.task_id,
        user_id=current_user.id,
        status=PushStatus.normal,
        push_method=schema_in.push_method,
        push_id=push_id,
    )
    await push.save()
    return CommonOut()
예제 #11
0
파일: order.py 프로젝트: 1445592270/market
async def cancel_pay(
    order_id: int, current_user: MarketAdminUser = Depends(require_super_scope_admin)
):
    """取消支付(线下订单)"""
    api_info = {}
    try:
        order = await UserOrder.get(id=order_id)
    except DoesNotExist:
        raise HTTPException(404, detail="订单未找到")
    if order.pay_method != PayMethod.offline:
        raise HTTPException(400, detail="仅线下支付订单支持支付确认")
    if order.status != OrderStatus.unpayed:
        raise HTTPException(400, detail="订单已支付 / 取消")
    order.status = OrderStatus.calceled
    await order.save()
    product = {}
    strategy_list = await StrategyPackage.filter(product_id=order.product_id)
    for i in strategy_list:
        product.update({'name':i.name})
    user_phone = await MarketUser.get(id = order.user_id)
    api_info.update({
        'phone': user_phone.phone,
        'actuallyPaid': order.payed_cash,
        'completeTime': int(time.time() * 1000),
        'costOfProduction': order.pay_cash,
        'orderNumber': order.id,
        'orderStatus': '取消支付',
        'packageName': product['name'],
        'paymentMethod': '线下支付',
        })
    res = await requests_url(api_info)
    print(res, 'res66666666666666')
    return CommonOut()
예제 #12
0
파일: market.py 프로젝트: 1445592270/game
async def add_market(
        schema_in: MarketCreate,
        current_user: MarketAdminUser = Depends(require_super_scope_su),
):
    """添加新的策略超市"""
    await StrategyMarket.create(**schema_in.dict(), status=MarketStatus.normal)
    return CommonOut()
예제 #13
0
async def check_email_dup(email: str):
    """检查邮箱是否重复"""
    try:
        await MarketUser.get_or_none(email=email)
    except DoesNotExist:
        raise HTTPException(status_code=404, detail="邮箱已注册")
    return CommonOut()
예제 #14
0
async def check_username_dup(user_name: str):
    """检查用户名是否重复"""
    try:
        await MarketUser.get_or_none(name=user_name)
    except DoesNotExist:
        raise HTTPException(status_code=404, detail="用户名已注册")
    return CommonOut()
예제 #15
0
async def check_phone_dup(phone: str):
    """检查手机号是否重复"""
    try:
        await MarketUser.get_or_none(phone=phone)
    except DoesNotExist:
        raise HTTPException(status_code=404, detail="手机号已注册")
    return CommonOut()
예제 #16
0
파일: tag.py 프로젝트: 1445592270/game
async def del_tag(schema_in: TagBatDel):
    """删除标签或风格,可传单个 id 或者 id 列表"""
    id_list = schema_in.id
    if isinstance(id_list, int):
        id_list = [id_list]
    await Tag.filter(id__in=id_list).update(deleted=True)
    return CommonOut()
예제 #17
0
async def recover_password(schema_in: ResetPassword):
    """
    Password Recovery
    """
    await verify_code(schema_in.vcode_id, schema_in.vcode)
    await verify_auth_code(schema_in.phone, schema_in.email,
                           schema_in.sms_code)
    if schema_in.phone:
        user = await MarketUser.get_or_none(phone=schema_in.phone)
    else:
        user = await MarketUser.get_or_none(email=schema_in.email)

    if not user:
        raise HTTPException(
            status_code=404,
            detail=
            "The user with this email/phone does not exist in the system.",
        )
    user.password = get_password_hash(schema_in.password, user.uuid.hex)
    await user.save()
    # verify_code = "1234"
    # if schema_in.phone:
    #     send_sms(verify_code)
    # else:
    #     send_email(verify_code)
    return CommonOut(msg="Password recovery message sent")
예제 #18
0
async def recover_password(schema_in: ResetPassword):
    """
    Password Recovery
    """
    await verify_code(schema_in.vcode_id, schema_in.vcode)
    await verify_auth_code(schema_in.phone, schema_in.email,
                           schema_in.sms_code)
    if schema_in.phone:
        user = await MarketUser.query.where(MarketUser.phone == schema_in.phone
                                            ).gino.first()
        #password = await MarketUser.select('password').where(MarketUser.phone==schema_in.phone).gino.scalar()
    else:
        user = await MarketUser.query.where(MarketUser.email == schema_in.email
                                            ).gino.first()
        #password = await MarketUser.select('password').where(MarketUser==schema_in.email).gino.scalar()

    if not user:
        #if not password:
        raise HTTPException(
            status_code=404,
            detail=
            "The user with this email/phone does not exist in the system.",
        )
    #await user.password == get_password_hash(schema_in.password)
    await user.update(
        password=get_password_hash(schema_in.password, user.uuid.hex)).apply()
    #await user.save()
    # verify_code = "1234"
    # if schema_in.phone:
    #     send_sms(verify_code)
    # else:
    #     send_email(verify_code)
    return CommonOut(msg="Password recovery message sent")
예제 #19
0
파일: strategy.py 프로젝트: 1445592270/game
async def get_strategy_code(task_id: str, request: Request):
    """检查是否需要因此策略信息"""
    if not await check_task_permission(TaskType.PAPER_TRADING, task_id, request):
        raise HTTPException(status.HTTP_403_FORBIDDEN, "没有权限")
    # get code
    query_str = "SELECT backtest_id FROM wk_simulation WHERE task_id=%s"
    client = Tortoise.get_connection("qpweb")
    try:
        rows = await client.execute_query_dict(query_str, task_id)
    except TypeError:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="复制错误,策略已不存在")
    if len(rows) != 1:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="复制错误,策略已不存在")
    backtest_id = rows[0]["backtest_id"]

    query_str = f"SELECT code FROM wk_strategy_backtest WHERE id=%s"
    try:
        rows = await client.execute_query_dict(query_str, backtest_id)
    except TypeError:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="复制错误,策略已不存在")
    if len(rows) != 1:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="复制错误,策略已不存在")

    code = rows[0]["code"]
    return CommonOut(data=code)
예제 #20
0
async def del_tag(schema_in: TagBatDel):
    """删除标签或风格,可传单个 id 或者 id 列表"""
    id_list = schema_in.id
    if isinstance(id_list, int):
        id_list = [id_list]
    await Tag.update.values(deleted=True).where(Tag.id.in_(id_list)
                                                ).gino.status()
    return CommonOut()
예제 #21
0
async def generate_verification_code():
    """生成验证码并存储到 redis"""
    code = generate_random_verify()
    data = get_image_verify(code)
    redis_id = "verify_" + str(time.time() % 10000)
    code = code.lower()
    await ctx.redis_client.set(redis_id, code, expire=config.VERIFY_CODE_TIMEOUT)
    return CommonOut(data={"id": redis_id, "code": data})
예제 #22
0
async def change_pkg_status(product_id: UUID, change_status: ListStatus):
    """更改套餐状态"""
    try:
        await StrategyPackage.filter(product_id=product_id
                                     ).update(status=change_status)
    except Exception:
        logger.exception("更新套餐 (%s) 状态失败:%s", product_id, change_status)
        raise HTTPException(status_code=400, detail="数据库错误")
    return CommonOut()
예제 #23
0
파일: order.py 프로젝트: 1445592270/market
async def confirm_pay(
    schema_in:OrderSearch,
    order_id: int, 
    current_user: MarketAdminUser = Depends(require_super_scope_admin)
):
    """确认支付(线下订单)"""
    api_info = {}
    try:
        order = await UserOrder.get(id=order_id)
    except DoesNotExist:
        raise HTTPException(404, detail="订单未找到")
    if order.pay_method != PayMethod.offline:
        raise HTTPException(400, detail="仅线下支付订单支持支付确认")
    if order.status != OrderStatus.unpayed:
        raise HTTPException(400, detail="订单已支付 / 取消")
    order.payed_cash = order.pay_cash
    order.pay_dt = datetime.datetime.now()
    order.expire_dt = datetime.datetime.now() + datetime.timedelta(
        days=order.total_days + order.coupon_days
    )
    order.status = OrderStatus.payed
    await order.save()
    await search_order_fake(schema_in)
    await search_order(schema_in)
    total_cash = []
    total_cash1 = {}
    order1 = await UserOrder.filter(user_id=order.user_id,status=OrderStatus.payed).prefetch_related('user')
    for i in order1:
        total_cash.append(i.total_cash)
        total_cash1.update({"phone":str(i.user.phone)})
    total_cash1.update({"strategicCost":str(sum(total_cash))})
    ress = await request_url(total_cash1)
    print(order.user_id,'user_id')
    print(order_id,'user_id22222222222222222')
    print(order1,'order11111111111111111111')
    print(total_cash1,'total_cash1')
    #print(ress,'ress')
    product = {}
    strategy_list = await StrategyPackage.filter(product_id=order.product_id)
    for i in strategy_list:
        product.update({'name':i.name})
    user_phone = await MarketUser.get(id = order.user_id)
    api_info.update({
        'phone': user_phone.phone,
        'actuallyPaid': order.payed_cash,
        'completeTime': int(time.time() * 1000),
        'costOfProduction': order.pay_cash,
        'orderNumber': order.id,
        'orderStatus': '支付成功',
        'packageName': product['name'],
        'paymentMethod': '线下支付',
        }
        )
    print(api_info, 'fake_api_info')
    res = await requests_url(api_info)
    print(res, 'res444444444444444')
    return CommonOut()
예제 #24
0
async def change_strategy_status(id_list: Union[str, List[str]],
                                 status: ListStatus):
    """直接重新上架策略"""
    if isinstance(id_list, str):
        id_list = [id_list]
    await QStrategy.filter(product_id__in=id_list).update(
        status=status,
        update_dt=datetime.datetime.now() - datetime.timedelta(hours=8))
    return CommonOut()
예제 #25
0
async def add_admin(
        schema_in: AdminUserCreate,
        current_user: MarketAdminUser = Depends(require_super_scope_su),
):
    """添加管理员,需要总后台超管权限"""
    if current_user.scope1 != "aq" or current_user.scope2 != UserScope2.su:
        return CommonOut(errCode=-100, errMsg="添加失败,没有权限")

    data = schema_in.dict()
    data["uuid"] = uuid.uuid1()
    data["password"] = get_password_hash(data["password"], data["uuid"].hex)
    try:
        await MarketAdminUser.create(**data)
    except Exception:
        logger.exception("create package failed: %s", schema_in.json())
        return CommonOut(errCode=-1, errMsg="添加失败,请检查名字是否重复")

    return CommonOut()
예제 #26
0
async def change_pkg_status(product_id: str, change_status: ListStatus):
    """更改套餐状态"""
    try:
        await StrategyPackage.update.values(status=change_status).where(
            StrategyPackage.product_id == product_id).gino.status()
    except Exception:
        logger.exception("更新套餐 (%s) 状态失败:%s", product_id, change_status)
        raise HTTPException(status_code=400, detail="数据库错误")
    return CommonOut()
예제 #27
0
async def change_strategy_status(id_list: Union[str, List[str]],
                                 status: ListStatus):
    """直接重新上架策略"""
    if isinstance(id_list, str):
        id_list = [id_list]
    await QStrategy.update.values(status=int(status)
                                  ).where(QStrategy.product_id.in_(id_list)
                                          ).gino.status()
    return CommonOut()
예제 #28
0
파일: tag.py 프로젝트: 1445592270/game
async def edit_tag(schema_in: TagUpdate):
    """编辑标签或者风格的名字"""
    try:
        await Tag.filter(id=schema_in.id).update(name=schema_in.name)
    except IntegrityError:
        raise HTTPException(status_code=400, detail="更新标签 / 风格失败,请检查名字是否重复")
    except Exception:
        logger.exception("create tag failed: %s", schema_in.json())
        raise HTTPException(status_code=400, detail="数据库错误")
    return CommonOut()
예제 #29
0
async def update_password(
    update_in: UpdatePassword,
    current_user: MarketAdminUser = Depends(require_active_admin)):
    if not verify_password(update_in.old_pwd, current_user.password,
                           current_user.uuid.hex):
        raise HTTPException(status_code=400, detail="密码错误")
    user = await MarketAdminUser.get(id=current_user.id)
    user.password = get_password_hash(update_in.new_pwd, current_user.uuid.hex)
    await user.save()
    return CommonOut()
예제 #30
0
파일: market.py 프로젝트: 1445592270/game
async def disable_market(
        schema_in: MarketDisable,
        current_user: MarketAdminUser = Depends(require_super_scope_su),
):
    """禁用 / 删除超市"""
    id_list = schema_in.id
    if isinstance(id_list, int):
        id_list = [id_list]
    await StrategyMarket.filter(id__in=id_list).update(status=schema_in.status)
    return CommonOut()