Ejemplo n.º 1
0
 def __init__(self, user_id):
     self.user_id = user_id
     self.yx_profile = HoardProfile.get(user_id)
     self.zw_profile = ZhiwangProfile.get(user_id)
     self.xm_profile = XMProfile.get(user_id)
     from core.models.hoarder.profile import HoarderProfile
     self.hoarder_profile = HoarderProfile(user_id)
Ejemplo n.º 2
0
def main():
    # 获取所有到期日在明天之前的资产
    tomorrow = date.today() + timedelta(days=1)

    with app.app_context():
        for index, asset in enumerate(
                get_redeeming_assets_by_period(tomorrow)):
            profile = ZhiwangProfile.add(asset.user_id)
            profile.synchronize_asset(asset.asset_no)
Ejemplo n.º 3
0
def order():
    """认购产品"""
    # 基础数据
    due_date = None
    profile = ZhiwangProfile.add(g.user.id_) if g.user else abort(401)
    bankcard_id = request.form.get('bankcard_id', type=int) or abort(400)
    bankcard = profile.bankcards.get(bankcard_id) or abort(400)
    if Partner.zw not in bankcard.bank.available_in:
        abort(400, 'unsupported bankcard')
    coupon_id = request.form.get('coupon_id', type=int, default=0)
    coupon = Coupon.get(coupon_id)
    if coupon and not coupon.is_owner(g.user):
        abort(403)
    product_id = request.form.get('product_id', type=int, default=0)
    product = ZhiwangProduct.get(product_id) or abort(404)
    wrapped_product_id = request.form.get('wrapped_product_id', type=int)
    wrapped_product = ZhiwangWrappedProduct.get(wrapped_product_id)
    if wrapped_product and not wrapped_product.is_qualified(g.user.id_):
        abort(401)

    # 选择表单验证
    form = select_subscribe_form(wrapped_product or product)()
    if not form.validate():
        return jsonify(r=False, error=form.errors.values()[0][0])

    # 只有房贷宝产品才有到期日
    if product.product_type is ZhiwangProduct.Type.fangdaibao:
        due_date = wrapped_product.due_date if wrapped_product else form.data[
            'due_date']

    # 设置购买卡为默认卡
    profile.bankcards.set_default(bankcard)

    # 申购产品
    try:
        order = subscribe_product(
            g.user,
            product,
            bankcard,
            form.data['order_amount'],
            form.data['pay_amount'],
            due_date,
            wrapped_product=wrapped_product,
            coupon=coupon,
            pocket_deduction_amount=form.data['pocket_deduction_amount'])
    except (SoldOutError, SuspendedError, OffShelfError, OutOfRangeError,
            InvalidIdentityError, ExceedBankAmountLimitError,
            SubscribeProductError, CouponBusinessError,
            FirewoodBusinessError) as e:
        return jsonify(r=False, error=unicode(e))

    payment_url = url_for('.pay',
                          order_code=order.order_code,
                          pay_code=order.pay_code)
    return jsonify(r=True, payment_url=payment_url)
Ejemplo n.º 4
0
def record():
    cur_path = 'record'
    yx_profile = HoardProfile.add(g.user.id_)
    zw_profile = ZhiwangProfile.add(g.user.id_)

    if not yx_profile and not zw_profile:
        return redirect(url_for('savings.landing.index'))

    filtered = bool(request.args.get('filter'))
    yx_orders = yx_profile.orders(filter_due=filtered)
    zw_mixins = zw_profile.mixins(filter_due=filtered)

    records = yx_orders + zw_mixins
    records = sorted(records, key=lambda x: x[0].creation_time, reverse=True)
    return render_template('savings/record.html',
                           records=records,
                           filter_due=filtered,
                           cur_path=cur_path)
Ejemplo n.º 5
0
def orders():
    """用户已有订单.

    :reqheader Authorization: OAuth 2.0 Bearer Token
    :reqheader If-None-Match: 客户端缓存的 ETag
    :resheader ETag: 客户端可缓存的 ETag
    :status 304: 客户端缓存未过期, 无需返回数据
    :status 200: 返回 :class:`.YixinOrderSchema` 、`.XinmiOrderSchema`  或 `.ZhiwangOrderSchema` 列表
    :query: 可选参数,按订单请求数限制返回结果. 目前可为:

                - ``"offset"`` 开始条数
                - ``"count"`` 每页数量
                - ``"only_due"`` 展示攒钱中的订单

    """
    yixin_order_schema = YixinOrderSchema(strict=True, many=True)
    zhiwang_order_schema = ZhiwangOrderSchema(strict=True, many=True)
    xm_order_schema = XinmiOrderSchema(strict=True, many=True)
    offset = request.args.get('offset', type=int, default=0)
    count = request.args.get('count', type=int, default=20)
    only_due = request.args.get('only_due', type=bool, default=False)
    order_data = []

    yixin_profile = HoardProfile.add(request.oauth.user.id_)
    yixin_orders = []
    for order, order_info, order_status in yixin_profile.orders(
            filter_due=only_due):
        order._coupon = None
        order._coupon_benefit = None
        order._order_status = order_status
        order._status_color = ORDER_STATUS_COLOR_MAP.get(
            order_status, '#9B9B9B')
        order._due_date = arrow_parse(order_info['frozenDatetime']).date()
        if order_status == u'确认中':
            order._confirm_desc = u'支付成功后1-3工作日'
        else:
            order._confirm_desc = order_info['startCalcDate']

        yixin_orders.append(order)
    order_data.extend(yixin_order_schema.dump(yixin_orders).data)

    zhiwang_profile = ZhiwangProfile.add(request.oauth.user.id_)
    zhiwang_orders = []
    for order, asset in zhiwang_profile.mixins(filter_due=only_due):
        order._display_status = asset.display_status if asset else order.display_status
        order._status_color = ORDER_STATUS_COLOR_MAP.get(
            order._display_status, '#9B9B9B')
        order._due_date = order.due_date.date()

        if order.display_status == u'处理中':
            order._confirm_desc = u'支付成功后第二个工作日'
        else:
            order._confirm_desc = order.start_date.date()
        zhiwang_orders.append(order)
    order_data.extend(zhiwang_order_schema.dump(zhiwang_orders).data)

    xm_profile = XMProfile.add(request.oauth.user.id_)
    xm_orders = []
    for order, asset in xm_profile.mixins(filter_due=only_due):
        order._display_status = asset.display_status if asset else order.display_status
        order._status_color = ORDER_STATUS_COLOR_MAP.get(
            order._display_status, '#9B9B9B')
        order._due_date = order.due_date.date()

        if order.display_status == u'处理中':
            order._confirm_desc = u'支付成功后第二个工作日'
        else:
            order._confirm_desc = order.start_date.date()
            xm_orders.append(order)
    order_data.extend(xm_order_schema.dump(xm_orders).data)

    if only_due:
        order_data = sorted(order_data, key=itemgetter('due_date'))
    else:
        order_data = sorted(order_data,
                            key=itemgetter('created_at'),
                            reverse=True)
    order_data = order_data[offset:offset + count]

    conditional_for(
        u'{0}#{1}#{2}'.format(o['uid'], unicode(o['status']), o['status_text'])
        for o in order_data)

    return jsonify(success=True, data=order_data)
Ejemplo n.º 6
0
def products():
    """攒钱助手待售产品.

    :query partner: 可选参数,按合作方支持情况限制返回结果. 目前可为:

                    - ``"zw"``  指旺
                    - ``"xm"``  新米

    :reqheader Authorization: OAuth 2.0 Bearer Token
    :reqheader If-None-Match: 客户端缓存的 ETag
    :resheader ETag: 客户端可缓存的 ETag
    :status 304: 客户端缓存未过期, 无需返回数据
    :status 200: 返回 :class:`.ProductSchema` 列表
    """
    from .products.consts import sale_display_text
    product_schema = ProductSchema(strict=True, many=True)

    partners = frozenset(request.args.getlist('partner'))
    profile = SavingsManager(request.oauth.user.id_)
    profile.refresh_profile()
    services = []

    def product_sale_status_to_text(product):
        is_early_morning_product = isinstance(
            product, (XMProduct, ZhiwangWrappedProduct))
        if product.in_stock:
            return sale_display_text['on_sale']
        elif product.is_taken_down:
            if is_early_morning_product:
                return sale_display_text['early_morning_off_sale']
            return sale_display_text['late_morning_off_sale']
        elif product.is_either_sold_out:
            if is_early_morning_product:
                return sale_display_text['early_morning_sold_out']
            return sale_display_text['late_morning_sold_out']

    if 'zw' in partners and zhiwang_fdb_product_on_switch.is_enabled:
        zw_services = []
        for s in ZhiwangProduct.get_all():
            if s.product_type is ZhiwangProduct.Type.fangdaibao:
                zw_services.append(s)
            elif s.product_type is ZhiwangProduct.Type.classic:
                if s.profit_period['min'] not in (OriginProfitPeriod(
                        90, 'day'), OriginProfitPeriod(
                            180, 'day'), OriginProfitPeriod(
                                270, 'day'), OriginProfitPeriod(365, 'day')):
                    zw_services.append(s)
        zw_services.sort(key=attrgetter('annual_rate'))
        ZhiwangProfile.add(request.oauth.user.id_)
        for zw_service in zw_services:
            product_text = product_sale_status_to_text(zw_service)
            if product_text:
                zw_service.button_display_text, zw_service.button_click_text = product_text
            zw_service.is_able_purchased = zw_service.in_stock
            zw_service.introduction = ''
            zw_service.title = ''
            zw_service.activity_title = ''
            zw_service.activity_introduction = ''
            zw_service._total_amount = 0
            zw_service.agreement = url_for('savings.landing.agreement_zhiwang',
                                           _external=True)
            zw_service.annotations = ZhiwangProduct.get_product_annotations(
                g.coupon_manager, zw_service)
        services.extend(zw_services)
    if 'xm' in partners:
        xm_products = [s for s in XMProduct.get_all()]
        xm_products.sort(key=attrgetter('annual_rate'))
        XMProfile.add(request.oauth.user.id_)
        for xm_product in xm_products:
            product_text = product_sale_status_to_text(xm_product)
            if product_text:
                xm_product.button_display_text, xm_product.button_click_text = product_text
            xm_product.is_able_purchased = xm_product.in_stock
            xm_product.introduction = ''
            xm_product.title = ''
            xm_product.activity_title = ''
            xm_product.activity_introduction = ''
            xm_product._total_amount = 0
            xm_product.agreement = url_for('savings.landing.agreement_xinmi',
                                           _external=True)
            xm_product.annotations = XMProduct.get_product_annotations(
                g.coupon_manager, xm_product)
        services.extend(xm_products)

    product_data = product_schema.dump(services).data
    for product in product_data:
        product.update({'is_newcomer': False})

    all_product_data = []

    if 'sxb' in partners:
        from .products.sxb import get_sxb_products

        product_schema = SxbProductSchema(strict=True, many=True)
        sxb_products = get_sxb_products(request.oauth.user.id_)
        services.extend(sxb_products)
        sxb_father_products = [
            p for p in sxb_products if p.kind is Product.Kind.father
        ]
        sxb_father_product_data = product_schema.dump(sxb_father_products).data
        if SavingsManager(request.oauth.user.id_).is_new_savings_user:
            sxb_child_products = [
                p for p in sxb_products if p.kind is Product.Kind.child
            ]
            sxb_child_product_data = product_schema.dump(
                sxb_child_products).data
            for product in sxb_child_product_data:
                product.update({'is_newcomer': True})
            all_product_data.extend(sxb_child_product_data)
        all_product_data.extend(sxb_father_product_data)

    all_product_data.extend(product_data)
    conditional_for(json.dumps(all_product_data))

    return jsonify(success=True, data=all_product_data)
Ejemplo n.º 7
0
def initialize():
    if not g.user:
        return redirect(url_for('accounts.login.login', next=request.path))
    g.zhiwang_profile = ZhiwangProfile.add(g.user.id_)
    g.coupon_manager = CouponManager(g.user.id_)
    g.firewood_flow = FirewoodWorkflow(g.user.id_)
Ejemplo n.º 8
0
 def get_savings_users(cls):
     return HoardProfile.get_savings_users().union(
         ZhiwangProfile.get_savings_users())
Ejemplo n.º 9
0
def orders():
    if not g.user:
        abort(401)

    limit = int(request.args.get('limit', 0))
    filtered = bool(request.args.get('filter'))
    info = {}
    savings_records = []

    yx_profile = HoardProfile.add(g.user.id_)
    zw_profile = ZhiwangProfile.add(g.user.id_)
    xm_profile = XMProfile.add(g.user.id_)
    yx_orders = yx_profile.orders(filter_due=filtered)
    zw_mixins = zw_profile.mixins(filter_due=filtered)
    xm_mixins = xm_profile.mixins(filter_due=filtered)

    placebo_order_ids = PlaceboOrder.get_ids_by_user(g.user.id_)
    placebo_orders = PlaceboOrder.get_multi(placebo_order_ids)
    if filtered:
        placebo_orders = [
            o for o in placebo_orders
            if o.status is not PlaceboOrder.Status.exited
        ]
    placebo_mixins = [(order, ) for order in placebo_orders]

    records = yx_orders + zw_mixins + xm_mixins + placebo_mixins
    if filtered:
        records = sorted(records, key=lambda x: x[0].due_date)
    else:
        records = sorted(records,
                         key=lambda x: x[0].creation_time,
                         reverse=True)
    saving_manager = SavingsManager(g.user.id_)

    info['plan_amount'] = yx_profile.plan_amount
    info['on_account_invest_amount'] = round_half_up(
        saving_manager.on_account_invest_amount, 2)
    info['fin_ratio'] = round_half_up(saving_manager.fin_ratio, 2)
    info['daily_profit'] = round_half_up(saving_manager.daily_profit, 2)
    info['total_profit'] = round_half_up(saving_manager.total_profit, 2)
    limit = limit if 0 < limit < len(records) else len(records)

    for record_info in records[:limit]:
        data = dict()
        base_record = record_info[0]
        exit_type = u'到期自动转回银行卡'

        if base_record.provider is yirendai:
            order, order_info, order_status = record_info
            rebates = HoardRebate.get_by_order_pk(order.id_)

            data['annual_rate'] = order.service.expected_income
            data['frozen_time'] = '%s 个月' % order.service.frozen_time
            data['order_status'] = order_status
            data['savings_money'] = order_info['investAmount']
            data['invest_date'] = order_info['investDate']
            data['exit_type'] = exit_type if order_info[
                'exitType'] == u'退回到划扣银行卡' else order_info['exitType']

            if rebates:
                data['rebates'] = HoardRebate.get_display(rebates)

            if order_status == u'确认中':
                data['interest_start_date'] = u'攒钱后1-3工作日'
            else:
                data['interest_start_date'] = order_info['startCalcDate']

            if order_status == u'已转出':
                data['income_amount'] = u'%s 元' % order_info['incomeAmount']
            else:
                data['expect_income_amount'] = u'%s 元' % order_info[
                    'expectedIncomeAmount']

            data['due_date'] = order.due_date.strftime('%Y-%m-%d')

            if order.bankcard:
                data['bankcard'] = u'%s (%s)' % (
                    order.bankcard.bank_name,
                    order.bankcard.display_card_number)
        elif base_record.provider is zhiwang:
            order, asset = record_info

            data['annual_rate'] = round_half_up(order.actual_annual_rate, 2)
            if order.profit_period.unit == 'day':
                data['frozen_time'] = '%s 天' % order.profit_period.value
            elif order.profit_period.unit == 'month':
                data['frozen_time'] = '%s 个月' % order.profit_period.value
            else:
                raise ValueError('invalid unit %s' % order.profit_period.unit)

            data[
                'order_status'] = asset.display_status if asset else order.display_status
            if order.profit_hikes:
                data['hikes'] = {
                    h.kind.label: h.display_text
                    for h in order.profit_hikes
                }
            data['savings_money'] = int(order.amount)
            data['invest_date'] = unicode(order.creation_time.date())
            data['exit_type'] = exit_type
            data['interest_start_date'] = order.start_date.strftime('%Y-%m-%d')
            if asset and asset.status == ZhiwangAsset.Status.redeemed:
                data['income_amount'] = u'%s 元' % round_half_up(
                    asset.current_interest, 2)
            else:
                # 尽可能显示已加息收益
                # FIXME (tonyseek) 这个做法太粗暴,有赖于资产的更新
                if order.asset:
                    expect_interest = order.asset.expect_interest
                else:
                    expect_interest = order.expect_interest
                data['expect_income_amount'] = u'%s 元' % round_half_up(
                    expect_interest, 2)
            data['due_date'] = order.due_date.strftime('%Y-%m-%d')

            data['contract_url'] = url_for(
                'savings.zhiwang.asset_contract',
                asset_no=asset.asset_no) if asset else ''
            if asset and asset.bankcard:
                # 指旺回款卡以资产的银行卡为准,可能会与订单中的不一致
                data['bankcard'] = u'%s (%s)' % (
                    asset.bankcard.bank.name,
                    asset.bankcard.display_card_number)
        elif base_record.provider is placebo:
            if base_record.status is PlaceboOrder.Status.failure:
                continue
            order = base_record
            profit_amount = order.calculate_profit_amount()
            profit_amount_text = u'%s 元' % round_half_up(profit_amount, 2)
            if base_record.status is PlaceboOrder.Status.exited:
                data['income_amount'] = profit_amount_text
            else:
                data['expect_income_amount'] = profit_amount_text
            data['annual_rate'] = round_half_up(order.profit_annual_rate, 2)
            data['frozen_time'] = order.profit_period.display_text
            data['order_status'] = order.status.display_text
            data['order_type'] = u'体验金'

            data['spring_festival'] = spring_promotion_switch.is_enabled

            data['savings_money'] = int(order.amount)
            data['invest_date'] = unicode(order.start_date)
            data['due_date'] = unicode(order.due_date.date())
            data['bankcard'] = u'%s (%s)' % (
                order.bankcard.bank.name, order.bankcard.display_card_number)
        elif base_record.provider is xmpay:
            order, asset = record_info

            data['annual_rate'] = round_half_up(order.actual_annual_rate, 2)
            if order.profit_period.unit == 'day':
                data['frozen_time'] = '%s 天' % order.profit_period.value
            elif order.profit_period.unit == 'month':
                data['frozen_time'] = '%s 个月' % order.profit_period.value
            else:
                raise ValueError('invalid unit %s' % order.profit_period.unit)

            data[
                'order_status'] = asset.display_status if asset else order.display_status
            if order.profit_hikes:
                data['hikes'] = {
                    h.kind.label: h.display_text
                    for h in order.profit_hikes
                }
            data['savings_money'] = int(order.amount)
            data['invest_date'] = unicode(order.creation_time.date())
            data['exit_type'] = exit_type
            data['interest_start_date'] = order.start_date.strftime('%Y-%m-%d')
            if asset and asset.status == XMAsset.Status.redeemed:
                data['income_amount'] = u'%s 元' % round_half_up(
                    asset.current_interest, 2)
            else:
                # 尽可能显示已加息收益
                if order.asset:
                    expect_interest = order.asset.expect_interest
                else:
                    expect_interest = order.expect_interest
                data['expect_income_amount'] = u'%s 元' % round_half_up(
                    expect_interest, 2)
            # 尽量使用第三方返回的到期日期。
            if order.asset:
                data['due_date'] = order.asset.interest_end_date.strftime(
                    '%Y-%m-%d')
            else:
                data['due_date'] = order.due_date.strftime('%Y-%m-%d')

            data['contract_url'] = url_for(
                'savings.xinmi.asset_contract',
                asset_no=asset.asset_no) if asset else ''
            if asset and asset.bankcard:
                # 投米回款卡以资产的银行卡为准,可能会与订单中的不一致
                data['bankcard'] = u'%s (%s)' % (
                    asset.bankcard.bank_name,
                    asset.bankcard.display_card_number)
        savings_records.append(data)
    return jsonify(r=True, records=savings_records, info=info)