Example #1
0
def listusertransactions(request):
    try:
        if not request.user.is_authenticated():
            return render(request, 'login.html', {'next': '/transhistory/'})
        username = request.user.username
        userId = request.user.id
        trans = ordermanager.get_user_transactions(userId, 'AXFund')
        pending_trans = []
        transactions = []
        for tran in trans:
            if tran.status == 'PENDING':
                pending_trans.append(create_trans_list_item(tran, 'AXFund'))
            else:
                transactions.append(create_trans_list_item(tran, 'AXFund'))
        accountinfo = useraccountinfomanager.get_user_accountInfo(
            request.user, 'AXFund', True)
        return render(
            request, 'html/translist.html', {
                'pending_trans': pending_trans,
                'transactions': transactions,
                'useraccountInfo': accountinfo
            })

    except Exception as e:
        error_msg = '出售美基金遇到错误: {0}'.format(sys.exc_info()[0])
        logger.exception(error_msg)
        return errorpage.show_error(request, ERR_CRITICAL_IRRECOVERABLE,
                                    '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))
Example #2
0
def heepay_confirm_payment(request):
    try:
        sitesettings = context_processor.settings(request)['settings']
        if request.method == 'POST':
            logger.info("Receive async payment notification ")
            json_data = get_payment_confirmation_json(
                request, sitesettings.heepay_app_key)
            if json_data is None:
                error_msg = 'Receive invalid notification from confirmation request, nothing to do'
                logger.error(error_msg)
                return HttpResponse(content='error')
            trade_status = json_data.get('trade_status', 'Unknown')
            if trade_status not in ['Success', 'Starting', 'PaySuccess']:
                error_msg = 'Receive notification with unsupported trade_status %s' % trade_status
                logger.error(error_msg)
                return HttpResponse(content='error')
            ordermanager.update_order_with_heepay_notification(
                json_data, 'admin')
            return HttpResponse(content='OK')
        else:
            logger.info("Receive sync payment notification")
            order_id = request.GET.get('order_id')
            if order_id is None:
                logger.error(
                    'heepay did not return with order_id with sync notification'
                )
                messages.error(request, '请稍后再查看您的买单')
            else:
                order = ordermanager.get_order_info(order_id)
                if order.status == 'PAYING':
                    logger.warn(
                        'purchse order {0} is still in PAYING mode'.format(
                            order_id))
                    messages.warning(request,
                                     '请等会确认付款完成'.format(order_id, order.units))
                elif order.status == 'PAID':
                    logger.info(
                        'purchse order {0} is already PAID'.format(order_id))
                    messages.success(request, '买单已发送,请等待卖方确认'.format(order_id))
                else:
                    logger.info(
                        'purchase order {0} has been filled'.format(order_id))
                    messages.success(request,
                                     '您的购买交易已完成,请看交易记录'.format(order_id))
                    return redirect('mytransactions')
        return redirect('purchase')
    except Exception as e:
        error_msg = 'Confirmation processing hit exception: {0}'.format(
            sys.exc_info()[0])
        logger.exception(error_msg)
        if request.method == 'GET':
            return errorpage.show_error(request, ERR_CRITICAL_IRRECOVERABLE,
                                        '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))
        else:
            return HttpResponse(content='error')
Example #3
0
def confirm_payment(request):
    try:
       if not request.user.is_authenticated():
          return render(request, 'login.html', { 'next_action' : '/mysellorder/'})
       order_id = request.POST['order_id']
       ordermanager.confirm_purchase_order(order_id, request.user.username)
       messages.success(request,'确认付款,交易完成')
       return redirect('sellorder')
    except Exception as e:
       error_msg = '确认付款遇到错误: {0}'.format(sys.exc_info()[0])
       logger.exception(error_msg)
       return errorpage.show_error(request, ERR_CRITICAL_IRRECOVERABLE,
              '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))
Example #4
0
def show_purchase_input(request):
    try:
        if not request.user.is_authenticated():
           return render(request, 'login.html', { 'next' : '/purchase/'})
        username = request.user.username
        userid = request.user.id
        useraccountInfo = useraccountinfomanager.get_user_accountInfo(request.user,'AXFund')
        if len(useraccountInfo.paymentmethods) == 0:
            messages.error(request, '请先注册支付方式再购买')
            return redirect('accountinfo')
        if len(useraccountInfo.paymentmethods[0].account_at_provider) == 0:
            messages.error(request, '请先注册支付账号再购买')
            return redirect('accountinfo')
        owner_user_id = request.POST["owner_user_id"]
        reference_order_id = request.POST["reference_order_id"]
        owner_login = request.POST["owner_login"]
        unit_price = float(request.POST["locked_in_unit_price"])
        total_units = 0
        if 'quantity' in request.POST:
           total_units = float(request.POST['quantity'])
        available_units = float(request.POST["available_units_for_purchase"])
        owner_payment_methods = ordermanager.get_user_payment_methods(owner_user_id)
        #for method in owner_payment_methods:
        #    print ("provider %s has image %s" % (method.provider.name, method.provider_qrcode_image))
        buyorder = OrderItem(
           '',
           userid,
           username,
           unit_price,'CYN',
           total_units, 0,
           0.0, 'AXFund',
           '','','BUY')
        return render(request, 'html/input_purchase.html',
               {'username': username,
                'buyorder': buyorder,
                'owner_user_id': owner_user_id,
                'reference_order_id': reference_order_id,
                'available_units_for_purchase': available_units,
                'owner_payment_methods': owner_payment_methods,
                'buyer_payment_methods': useraccountInfo.paymentmethods }
               )
    except Exception as e:
       error_msg = '显示买单出现错误: {0}'.format(sys.exc_info()[0])
       logger.exception(e)
       return errorpage.show_error(request, ERR_CRITICAL_IRRECOVERABLE,
              '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))
Example #5
0
def accountinfo(request):
    try:
        if not request.user.is_authenticated():
            return render(request, 'login.html',
                          {'next': '/accounts/accountinfo/'})
        useraccountInfo = useraccountinfomanager.get_user_accountInfo(
            request.user, 'AXFund')
        request.session[REQ_KEY_USERACCOUNTINFO] = useraccountInfo.tojson()
        return render(
            request, 'html/myaccount.html', {
                'useraccountInfo': useraccountInfo,
                REQ_KEY_USERNAME: request.user.username
            })
    except Exception as e:
        error_msg = '用户主页显示遇到错误: {0}'.format(sys.exc_info()[0])
        logger.exception(error_msg)
        return errorpage.show_error(request, ERR_CRITICAL_IRRECOVERABLE,
                                    '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))
Example #6
0
def external_address(request):
    try:
        if not request.user.is_authenticated():
            return render(request, 'login.html',
                          {'next': '/accounts/accountinfo/'})
        externaladdress = None
        if request.method == 'GET':
            # if there's id parameter, this is view/update request,
            # query the object first and show
            if 'id' in request.GET:
                id = 0
                id_str = request.GET['id']
                if len(id_str) > 0:
                    id = int(id_str)
                logger.info('Get user {0}\'s external address by {1}'.format(
                    request.user.username, id))
                externaladdress = useraccountinfomanager.get_user_externaladdr_by_id(
                    id)
            else:
                externaladdress = None
            return render(request, 'html/update_external_address.html',
                          {'user_external_address': externaladdress})
        else:
            id = 0
            id_str = request.POST['id']
            if len(id_str) > 0:
                id = int(id_str)
            address = request.POST['address']
            alias = request.POST['alias']
            crypto = request.POST['crypto']
            if len(crypto) == 0:
                crypto = 'AXFund'
            externaladdress = UserExternalWalletAddressInfo(
                id, request.user.id, alias, address, crypto)
            if not useraccountinfomanager.create_update_externaladdr(
                    externaladdress, request.user.username):
                messages.error(request, "您的提币地址属于交易平台注入地址,请修改您的提币地址")
            return redirect('accountinfo')
    except Exception as e:
        error_msg = '添加/修改提币抵制遇到错误: {0}'.format(sys.exc_info()[0])
        logger.exception(error_msg)
        return errorpage.show_error(request, ERR_CRITICAL_IRRECOVERABLE,
                                    '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))
Example #7
0
def payment_method(request):
    # TO DO: pass down request.user to controller.

    try:
        if not request.user.is_authenticated():
            return render(request, 'login.html',
                          {'next': '/accounts/accountinfo/'})
        if request.method == 'GET':
            payment_providers = userpaymentmethodmanager.get_payment_providers(
            )
            user_payment_methods = userpaymentmethodmanager.get_user_payment_methods(
                request.user.id)
            return render(
                request, 'html/update_payment_method.html', {
                    'user_payment_methods': user_payment_methods,
                    'payment_providers': payment_providers
                })
        else:
            str_val = request.POST['payment_method_id']
            payment_method_id = int(str_val) if len(str_val) > 0 else 0
            payment_provider = request.POST['payment_provider']
            account = request.POST['account']

            has_error = False
            if len(payment_provider) == 0:
                has_error = True
                messages.error(request, '请选择支付方式')
            elif len(account) == 0:
                has_error = True
                messages.error(request, '请输入您的账号')
            if has_error:
                return redirect('paymentmethods')
            record = UserPaymentMethodView(payment_method_id, request.user.id,
                                           payment_provider, '', account, '')
            userpaymentmethodmanager.create_update_user_payment_method(
                record, request.user.username)
            return redirect('accountinfo')
    except Exception as e:
        error_msg = 'sell_axfund hit exception'
        logger.exception(error_msg)
        return errorpage.show_error(request, ERR_CRITICAL_IRRECOVERABLE,
                                    '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))
Example #8
0
def show_active_sell_orders(request):
    try:
       logger.debug("get show show_active_sell_orders request")

       if not request.user.is_authenticated():
           return render(request, 'login.html', { 'next' : '/purchase/'})
       username = request.user.username
       status = None
       sellorders = ordermanager.get_all_open_seller_order_exclude_user(request.user.id)
       accountinfo = useraccountinfomanager.get_user_accountInfo(request.user, 'AXFund')
       return render(request, 'html/purchase.html', {'sellorders': sellorders,
                REQ_KEY_USERNAME: username,
                'useraccountInfo': accountinfo,
                'previous_call_status' : status})

    except Exception as e:
       error_msg = '显示现有卖单出现错误: {0}'.format(sys.exc_info()[0])
       logger.exception(e)
       return errorpage.show_error(request, ERR_CRITICAL_IRRECOVERABLE,
              '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))
Example #9
0
def redeem(request):
    try:
       if not request.user.is_authenticated():
          return render(request, 'login.html', { 'next' : '/accounts/accountinfo/'})
       if request.method=='POST':
           userid = request.user.id
           toaddr = request.POST['toaddress']
           amount = float(request.POST['quantity'])
           crypto = request.POST['crypto']
           if not redeemmanager.check_send_to_address(crypto, toaddr):
               logger.info("Failed the address check")
               messages.error(request, "您的提币地址属于交易平台注入地址,请修改您的提币地址")
               return redirect('accountinfo')
           logger.info("Pass the address check")
           sitesettings = context_processor.settings(request)['settings']
           axfd_bin_path = sitesettings.axfd_path
           axfd_datadir = sitesettings.axfd_datadir
           axfd_passphrase = sitesettings.axfd_passphrase
           wallet_account_name = sitesettings.axfd_account_name
           axfd_account = sitesettings.axfd_account_name
           lookback_count = sitesettings.axfd_list_trans_count
           axfd_tool = AXFundUtility(axfd_bin_path, axfd_datadir,
                wallet_account_name)
           axfd_tool.unlock_wallet(axfd_passphrase, 15)
           operation_comment = 'UserId:{0},redeem:{1},to:{2}'.format(
               userid, amount, toaddr)
           trx = axfd_tool.send_fund(axfd_account, toaddr, amount,
                   operation_comment,lookback_count)
           redeem_cmd = RedeemItem(userid, toaddr, amount, crypto)
           redeemmanager.redeem(redeem_cmd,request.user.username,
              trx['txid'], math.fabs(trx['fee']),
              operation_comment)
           return redirect('accountinfo')
       else:
           return HttpBadRequestResponse('The method can not be GET for redeem')
    except Exception as e:
       error_msg = '提币遇到错误: {0}'.format(sys.exc_info()[0])
       logger.exception(error_msg)
       return errorpage.show_error(request, ERR_CRITICAL_IRRECOVERABLE,
              '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))
Example #10
0
def cancel_sell_order(request):
    try:
       if not request.user.is_authenticated():
          return render(request, 'login.html', { 'next_action' : '/mysellorder/'})
       username = request.user.username
       userId = request.user.id
       if request.method == 'POST':
           orderid = request.POST['order_id']
           ordermanager.cancel_sell_order(userId, orderid, 'AXFund', username)

       return redirect('sellorder')
    except ValueError as ve:
       if ve.args[0] == "ORDER_USED_OR_LOCKED_CANCELLED":
           logger.exception("Cancel hit exception: {0} ".format(ve.args[0]))
           messages.error(request, "您选择的卖单有待完成买单,或在锁定,取消状态")
           return redirect('sellorder')
       else:
           raise
    except Exception as e:
       error_msg = '撤销美基金卖单遇到错误: {0}'.format(sys.exc_info()[0])
       logger.exception(error_msg)
       return errorpage.show_error(request, ERR_CRITICAL_IRRECOVERABLE,
              '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))
Example #11
0
def sell_axfund(request):
    try:
       if not request.user.is_authenticated():
          return render(request, 'login.html', { 'next' : '/mysellorder/'})
       accountinfo = useraccountinfomanager.get_user_accountInfo(request.user, 'AXFund')
       if len(accountinfo.paymentmethods) == 0:
           messages.error(request, '请先注册支付方式再挂卖单')
           return redirect('accountinfo')
       if len(accountinfo.paymentmethods[0].account_at_provider) == 0:
           messages.error(request, '请先注册支付账号再挂卖单')
           return redirect('accountinfo')
       if request.method == 'POST':
          request_source = request.POST['request_source']
          # this indicate that the request come from submit
          # order instead of refresh a response page of previous
          # order
          if len(request_source) > 0:
              order_command = read_order_input(request)
              if order_command.total_units - accountinfo.available_balance < 0:
                  ordermanager.create_sell_order(order_command, request.user.username)
                  messages.success(request,'您的卖单已经成功创建')
              else:
                  messages.error(request, '卖单数量不可以高于可用余额')
       sellorders = ordermanager.get_sell_transactions_by_user(request.user.id)
       if request.method == 'POST':
           return redirect('sellorder')
       else:
           return render(request, 'html/mysellorder.html',
               {'sellorders': sellorders,
                'useraccountInfo': accountinfo})

    except Exception as e:
       error_msg = '出售美基金遇到错误: {0}'.format(sys.exc_info()[0])
       logger.exception(error_msg)
       return errorpage.show_error(request, ERR_CRITICAL_IRRECOVERABLE,
              '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))
Example #12
0
def create_purchase_order(request):
    try:
        logger.debug('create_purchase_order()...')
        if not request.user.is_authenticated():
            logger.error("user session is not valid.  Go to logout")
            return render(request, 'login.html', { 'next': '/purchase/'})
        username = request.user.username
        userid = request.user.id
        logger.info("Begin process user input for creating purchase order")
        if request.method == 'POST':
            reference_order_id = request.POST['reference_order_id']
            owner_user_id = int(request.POST["owner_user_id"])
            quantity = float(request.POST['quantity'])
            available_units = float(request.POST['available_units'])
            unit_price = float(request.POST['unit_price'])
            seller_payment_provider = request.POST['seller_payment_provider']
            crypto= request.POST['crypto']
            total_amount = float(request.POST['total_amount'])
            buyorder = OrderItem('', userid, username, unit_price, 'CNY', quantity,
                0, total_amount, crypto, '', '','BUY')
            buyorderid = None
            try:
                buyorderid = ordermanager.create_purchase_order(buyorder,
                     reference_order_id,
                     seller_payment_provider, username)
            except ValueError as ve:
                if ve.args[0] == 'SELLORDER_NOT_OPEN':
                    messages.error(request, '卖单暂时被锁定,请稍后再试')
                elif ve.args[0] == 'BUY_EXCEED_AVAILABLE_UNITS':
                    messages.error(request,'购买数量超过卖单余额,请按撤销键然后再试')
                else:
                    raise
                owner_payment_methods = ordermanager.get_user_payment_methods(owner_user_id)
                useraccountInfo = useraccountinfomanager.get_user_accountInfo(request.user,'AXFund')
                redirect('purchase')
            if buyorderid is None:
               raise ValueError('Failed to get purchase order id')

            returnstatus = None

            # read the sitsettings
            sitesettings = context_processor.settings(request)['settings']
            json_response = send_payment_request(sitesettings, seller_payment_provider,
                buyorder.order_id, total_amount)
            if json_response is not None and json_response['return_code'] == 'SUCCESS':
                if ordermanager.post_open_payment_order(
                                buyorderid, 'heepay',
                                json_response['hy_bill_no'],
                                json_response['hy_url'],
                                username):

                    qrcode_file = generate_payment_qrcode('heepay', json_response, settings.MEDIA_ROOT)
                    return render(request, 'html/purchase_heepay_qrcode.html',
                         { 'total_units' : quantity, 'unit_price': unit_price,
                           'total_amount': total_amount,
                           'heepay_qrcode_file' : qrcode_file })
            owner_payment_methods = ordermanager.get_user_payment_methods(owner_user_id)
            useraccountInfo = useraccountinfomanager.get_user_accountInfo(request.user,'AXFund')
            # sample reply error : {"return_code":"FAIL","return_msg":"无效的total_fee"}
            messages.error(request, '向汇钱包下单申请失败:{0}'.format(json_response['return_msg'].encode("utf-8")))
            redirect('purchase')

    except Exception as e:
        error_msg = '创建买单遇到错误: {0}'.format(sys.exc_info()[0])
        logger.exception(error_msg)
        return errorpage.show_error(request, ERR_CRITICAL_IRRECOVERABLE,
              '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))