Exemple #1
0
def pay_to_log(user, product, classbook_device, end_buy=False):
    if classbook_device and check_free_for_classbook(product['clsb_category']['id']):
        return True
    if not check_free_for_classbook(product['clsb_category']['id']):
        downloaded = db(db.clsb_download_archieve.product_id == product['clsb_product']['id'])(db.clsb_download_archieve.status.like("Completed"))(db.clsb_download_archieve.user_id == user['id']).select()
        if len(downloaded) > 0:
            return True
    """
    Mua cho thiet bi class book voi gia sach SGK se ko ghi log
    """
    import applications.cbs20.modules.transaction as transaction
    check_buy = db(db.clsb30_product_history.product_id == product['clsb_product']['id'])(db.clsb30_product_history.user_id == user['id']).select()
    if len(check_buy) > 0:
        return True
    if not end_buy:
        user_cash = db(db.clsb_user.id == user['id']).select(db.clsb_user.fund, db.clsb_user.data_sum).as_list()
        user_cash = user_cash[0]['fund']
        new_fund = user_cash - product['clsb_product']['product_price']
        if new_fund < 0:
            return dict(error='Tiền trong tài khoản không đủ')

        data_sum = transaction.encrypt(new_fund, user['username'])
        db(db.clsb_user.username == user['username']).update(fund=new_fund, data_sum=data_sum)

        user_id = db(db.clsb_user.username == user['username']).select().first()['id']
        data = dict(record_id=user_id, table_name='clsb_user', key_unique='username')
        insert_to_log_temp(data)
        # url_update_fund = URL(host=DOMAIN_VDC, a='cbs20', c="sync2vdc", f="update_user_fund",
        #                       vars=dict(fund=new_fund, data_sum=data_sum, username=user['username']))
        # print(url_update_fund)
        # urllib2.urlopen(url_update_fund)
    if len(db(db.clsb30_product_history.product_id == product['clsb_product']['id'])(db.clsb30_product_history.user_id == user['id']).select()) <= 0:
        insert_buy = db.clsb30_product_history.insert(
            product_title=product['clsb_product']['product_title'],
            product_id=product['clsb_product']['id'],
            user_id=user['id'],
            category_id=product['clsb_category']['id'],
            product_price=product['clsb_product']['product_price']
        )
        data = dict(record_id=str(insert_buy), table_name='clsb30_product_history', key_unique='user_id.product_id')
        insert_to_log_temp(data)
        # url_sign = URL(host=DOMAIN_VDC, a='cbs20', c="sync2vdc", f="sign_buy_product", args=["Product",
        #                                                                                     product['clsb_product']['id'],
        #                                                                                     user['username'],
        #                                                                                     product['clsb_category']['id'],
        #                                                                                     pay])
        # print(url_sign)
        # urllib2.urlopen(url_sign)
    return True
Exemple #2
0
def pay(username, total, product_id, oldCBM):
    import applications.cbs.modules.transaction as transaction
    #message content to send user
    message = 'Tài khoản của bạn đã bị khóa, vui lòng liên hệ với quản trị viên để biết thêm chi tiết !'
    subject = 'Tài khoản ClassBook bị khóa'
    user_id = db(db.clsb_user.username == username).select(
        db.clsb_user.id).as_list()[0]['id']
    if not user_id:
        return CB_0010  # Tên đăng nhập không tồn tại
    rows = db(db.clsb_download_archieve.user_id == user_id)(db.clsb_download_archieve.product_id == product_id)\
        .select(db.clsb_download_archieve.status).as_list()
    if rows:
        return CB_0000  # SUCCES

    # total = request.args(1)
    # username = request.args(0)
    user_cash = db(db.clsb_user.username == username).select(
        db.clsb_user.fund, db.clsb_user.data_sum).as_list()
    user_cash = user_cash[0]['fund']
    if user_cash < total or user_cash < 0:
        return dict(error=CB_0023)

    try:
        #if db.clsb_user.data_sum != transaction.encrypt(db, user_cash, username):
        #db(db.clsb_user.username == username).update(status=False)
        # send mail to user
        # get user email
        #user_email = db(db.clsb_user.username == username).select(db.clsb_user.email).as_list()
        #user_email = user_email[0]['email']
        #try:
        #    mail.send(to=[user_email], subject=subject, message=message)
        #    return dict(item=CB_0000)
        #except Exception as e:
        #    print str(e)
        #    return dict(error=CB_0006)
        #return CB_0006
        if oldCBM:
            new_fund = db.clsb_user.fund - total / 2
        else:
            new_fund = db.clsb_user.fund - total

        data_sum = transaction.encrypt(db, new_fund, username)
        db(db.clsb_user.username == username).update(fund=new_fund,
                                                     data_sum=data_sum)
        return CB_0000  # SUCCESS
    except Exception as e:
        print "Error at pay() in modules/transaction.py: " + str(e)
        return CB_0003  # DB_RQ_FAILD
Exemple #3
0
def test_transaction():
    buyer_id = 8289
    user_name = '*****@*****.**'
    nl_token = "test"
    nl_data = dict()
    nl_data['total_amount'] = 2000
    nl_data["order_code"] = 8793
    nl_data["transaction_id"] = "20614912"
    if True:
        if True:
            if True:
                if True:
                    if True:
                        try:
                            old_fund = db(db.clsb_user.id == buyer_id).select(
                                db.clsb_user.fund)[0].fund
                            if isinstance(old_fund, (int, long)):
                                new_fund = int(old_fund)
                                new_fund += int(nl_data["total_amount"])
                                data_sum = encrypt(new_fund, user_name)
                                db(db.clsb_user.id == buyer_id).update(
                                    fund=new_fund, data_sum=data_sum)
                            else:
                                return dict(error="Error fund")
                            order_code = nl_data["order_code"]
                            q = db(db.clsb_transaction.id == order_code)
                            payment_type = q.select().first()['payment_type']
                            amount = int(nl_data["total_amount"])
                            face_value = amount
                            real_value = amount
                            if payment_type == "VISA":
                                face_value = amount
                                real_value = amount * 0.97 - 5000
                            elif payment_type == "ATM_ONLINE":
                                face_value = amount
                                real_value = amount * 0.985 - 500
                            q.update(status="COMPLETE",
                                     amount=nl_data["total_amount"],
                                     token=nl_token,
                                     face_value=face_value,
                                     real_value=real_value,
                                     order_code=nl_data["order_code"],
                                     merchant_id=nl_data["transaction_id"])
                            return nl_data["total_amount"]
                        except Exception as ex:
                            return dict(error=str(ex) + " on line " +
                                        str(sys.exc_traceback.tb_lineno))
Exemple #4
0
def pay_to_log(user, product, classbook_device, end_buy=False):
    if classbook_device and check_free_for_classbook(
            product['clsb_category']['id']):
        return True
    if not check_free_for_classbook(product['clsb_category']['id']):
        downloaded = db(
            db.clsb_download_archieve.product_id == product['clsb_product']
            ['id'])(db.clsb_download_archieve.status.like("Completed"))(
                db.clsb_download_archieve.user_id == user['id']).select()
        if len(downloaded) > 0:
            return True
    """
    Mua cho thiet bi class book voi gia sach SGK se ko ghi log
    """
    import applications.cbs20.modules.transaction as transaction
    check_buy = db(
        db.clsb30_product_history.product_id == product['clsb_product']['id'])(
            db.clsb30_product_history.user_id == user['id']).select()
    if len(check_buy) > 0:
        return True
    if not end_buy:
        user_cash = db(db.clsb_user.id == user['id']).select(
            db.clsb_user.fund, db.clsb_user.data_sum).as_list()
        user_cash = user_cash[0]['fund']
        new_fund = user_cash - product['clsb_product']['product_price']
        if new_fund < 0:
            return dict(error='Tiền trong tài khoản không đủ')

        data_sum = transaction.encrypt(new_fund, user['username'])
        db(db.clsb_user.username == user['username']).update(fund=new_fund,
                                                             data_sum=data_sum)

        user_id = db(
            db.clsb_user.username == user['username']).select().first()['id']
    if len(
            db(db.clsb30_product_history.product_id == product['clsb_product']
               ['id'])
        (db.clsb30_product_history.user_id == user['id']).select()) <= 0:
        insert_buy = db.clsb30_product_history.insert(
            product_title=product['clsb_product']['product_title'],
            product_id=product['clsb_product']['id'],
            user_id=user['id'],
            category_id=product['clsb_category']['id'],
            product_price=product['clsb_product']['product_price'])
    return True
Exemple #5
0
def pay_to_log_divide(user,
                      product,
                      classbook_device,
                      isMedia,
                      pay,
                      end_buy=False):
    # if classbook_device and check_free_for_classbook(product['clsb_category']['id']):
    #     print('return1')
    #     return "True 1"
    # if isMedia.lower() == 'false':
    #     if not check_free_for_classbook(product['clsb_category']['id']):
    #         downloaded = db(db.clsb_download_archieve.product_id == product['clsb_product']['id'])(db.clsb_download_archieve.status.like("Completed"))(db.clsb_download_archieve.user_id == user['id']).select()
    #         if len(downloaded) > 0:
    #             #print('return2')
    #             return "True 2"
    """
    Mua cho thiet bi class book voi gia sach SGK se ko ghi log
    """
    import applications.cbs20.modules.transaction as transaction

    if isMedia.lower() == 'true':
        check_buy = db(
            db.clsb30_media_history.product_id == product['clsb_product']
            ['id'])(db.clsb30_media_history.user_id == user['id']).select()
        #print(check_buy)
        if len(check_buy) > 0:
            #print('return3')
            return "True 3"
    else:
        check_buy = db(
            db.clsb30_product_history.product_id == product['clsb_product']
            ['id'])(db.clsb30_product_history.user_id == user['id']).select()
        #print(check_buy)
        if len(check_buy) > 0:
            #print('return4')
            return "True 4"
    if not end_buy:
        user_cash = db(db.clsb_user.id == user['id']).select(
            db.clsb_user.fund, db.clsb_user.data_sum).as_list()
        user_cash = user_cash[0]['fund']
        new_fund = int(user_cash) - int(pay)
        if new_fund < 0:
            #print('return5')
            return dict(error='Tiền trong tài khoản không đủ')
        data_sum = transaction.encrypt(new_fund, user['username'])
        db(db.clsb_user.username == user['username']).update(fund=new_fund,
                                                             data_sum=data_sum)

        user_id = db(
            db.clsb_user.username == user['username']).select().first()['id']
    if isMedia.lower() == 'true':
        if len(
                db(db.clsb30_media_history.product_id ==
                   product['clsb_product']['id'])
            (db.clsb30_media_history.user_id == user['id']).select()) <= 0:
            media_insert = db.clsb30_media_history.insert(
                product_title=product['clsb_product']['product_title'],
                product_id=product['clsb_product']['id'],
                user_id=user['id'],
                category_id=product['clsb_category']['id'],
                product_price=pay)

            params = {
                'searchTxt': 'ND',
                'clientIP': '',
                'dserial': "",
                'pcode': product['clsb_product']['product_code'],
                'purchase_type': 'WEB_PAY',
                'rom_version': "CLASSBOOK.APP",
                'userID': user_id,
                'price': int(pay),
                'status': 'Completed'
            }
            log_20(params, True)

            db.clsb30_payment_log.insert(
                user_id=user_id,
                product_id=product['clsb_product']['id'],
                product_type='MEDIA',
                pay=int(pay))

    else:
        try:
            if len(
                    db(db.clsb30_product_history.product_id ==
                       product['clsb_product']['id'])(
                           db.clsb30_product_history.user_id ==
                           user['id']).select()) <= 0:
                product_insert = db.clsb30_product_history.insert(
                    product_title=product['clsb_product']['product_title'],
                    product_id=product['clsb_product']['id'],
                    user_id=user['id'],
                    category_id=product['clsb_category']['id'],
                    product_price=pay)
                params = {
                    'searchTxt': 'ND',
                    'clientIP': '',
                    'dserial': "",
                    'pcode': product['clsb_product']['product_code'],
                    'purchase_type': 'WEB_PAY',
                    'rom_version': "CLASSBOOK.APP",
                    'userID': user_id,
                    'price': int(pay),
                    'status': 'Completed'
                }
                log_20(params, True)
                db.clsb30_payment_log.insert(
                    user_id=user_id,
                    product_id=product['clsb_product']['id'],
                    product_type='PRODUCT',
                    pay=int(pay))
        except Exception as err:
            print("Error: " + err)
            return dict(error=str(err))
    return "True final"
Exemple #6
0
def pay(username, total, product_id, oldCBM):
    import applications.cbs.modules.transaction as transaction
    try:
        #message content to send user
        message = 'Tài khoản của bạn đã bị khóa, vui lòng liên hệ với quản trị viên để biết thêm chi tiết !'
        subject = 'Tài khoản ClassBook bị khóa'
        user_id = db(db.clsb_user.username == username).select(
            db.clsb_user.id).as_list()[0]['id']
        if not user_id:
            return CB_0010  # Tên đăng nhập không tồn tại

        # total = request.args(1)
        # username = request.args(0)
        user_cash = db(db.clsb_user.username == username).select(
            db.clsb_user.fund, db.clsb_user.data_sum).as_list()
        user_cash = user_cash[0]['fund']

        # remove check user_cash /TanBM 03/01/201
        # if user_cash < total or user_cash < 0:
        #     return dict(error=CB_0023)

        #if db.clsb_user.data_sum != transaction.encrypt(db, user_cash, username):
        #db(db.clsb_user.username == username).update(status=False)
        # send mail to user
        # get user email
        #user_email = db(db.clsb_user.username == username).select(db.clsb_user.email).as_list()
        #user_email = user_email[0]['email']
        #try:
        #    mail.send(to=[user_email], subject=subject, message=message)
        #    return dict(item=CB_0000)
        #except Exception as e:
        #    print str(e)
        #    return dict(error=CB_0006)
        #return CB_0006

        # check new purchase
        new_fund = user_cash
        query = db(db["clsb_product"].id == product_id)
        query = query(db["clsb20_product_purchase_item"].product_code ==
                      db["clsb_product"].product_code)
        query = query(db["clsb20_purchase_item"].id ==
                      db["clsb20_product_purchase_item"].purchase_item)
        query = query(db["clsb20_purchase_type"].id ==
                      db["clsb20_purchase_item"].purchase_type)
        product_purchases = query.select(
            # db["clsb20_product_purchase_item"].discount,
            db["clsb20_purchase_type"].name,
            # db["clsb20_purchase_type"].name, db["clsb20_purchase_item"].times,
            db["clsb20_purchase_item"].duration,
            db['clsb20_purchase_item'].id)
        if len(product_purchases) == 0:
            rows = db((db.clsb_download_archieve.user_id == user_id)
                      & (db.clsb_download_archieve.product_id == product_id)
                      & (db.clsb_download_archieve.status.like("Completed")
                         | db.clsb_download_archieve.status.like("TestSuccess")
                         )).select(db.clsb_download_archieve.status)
            if len(rows) > 0:
                pass
            else:
                if oldCBM:
                    new_fund -= total / 2
                else:
                    new_fund -= total
        else:
            from datetime import datetime
            from datetime import timedelta
            product_purchase = product_purchases.first()
            if product_purchase.clsb20_purchase_type.name.upper() != "FREE":
                if product_purchase.clsb20_purchase_type.name.upper(
                ) != "NONCONSUMABLE":
                    query = db(
                        db["clsb20_user_purchase_item"].user_id == user_id)
                    query = query(db["clsb20_user_purchase_item"].purchase_id
                                  == product_purchase.clsb20_purchase_item.id)
                    user_purchases = query.select(
                        db["clsb20_user_purchase_item"].id,
                        # db["clsb20_user_purchase_item"].times,
                        db["clsb20_user_purchase_item"].day_end)
                    is_expired_date_or_time = False
                    if len(user_purchases) > 0:
                        user_purchase = user_purchases.first()
                        # if user_purchase.times > 0:
                        #     db(db["clsb20_user_purchase_item"].id == user_purchase.id).update(times=user_purchase.times-1)
                        # elif user_purchase.times < 0 or user_purchase.day_end > datetime.today():
                        #     pass
                        # else:
                        #     if oldCBM:
                        #         new_fund -= total / 2
                        #     else:
                        #         new_fund -= total
                        #     day_end = datetime.today() + timedelta(days=product_purchase.clsb20_purchase_item.duration)
                        #     query = db(db["clsb20_user_purchase_item"].id == user_purchase.id)
                        #     query.update(day_end=day_end, times=product_purchase.clsb20_purchase_item.times)
                        #     db["clsb20_purchase_renew_history"].insert(user_id=user_id, product_id=product_id, date_do_renew=datetime.today())
                        if oldCBM:
                            new_fund -= total / 2
                        else:
                            new_fund -= total
                        day_end = datetime.today() + timedelta(
                            days=product_purchase.clsb20_purchase_item.duration
                        )
                        query = db(db["clsb20_user_purchase_item"].id ==
                                   user_purchase.id)
                        query.update(day_end=day_end)
                        # , times=product_purchase.clsb20_purchase_item.times)
                        db["clsb20_purchase_renew_history"].insert(
                            user_id=user_id,
                            product_id=product_id,
                            date_do_renew=datetime.today())
                    else:
                        if oldCBM:
                            new_fund -= total / 2
                        else:
                            new_fund -= total
                        # if product_purchase.clsb20_purchase_item.times == 0:
                        #     day_end = datetime.today() + timedelta(days=product_purchase.clsb20_purchase_item.duration)
                        #     db["clsb20_user_purchase_item"].insert(user_id=user_id, product_id=product_id,
                        #                                            times=product_purchase.clsb20_purchase_item.times,
                        #                                            day_end=day_end)
                        #     db["clsb20_purchase_renew_history"].insert(user_id=user_id, product_id=product_id,
                        #                                            date_do_renew=datetime.today())
                        day_end = datetime.today() + timedelta(
                            days=product_purchase.clsb20_purchase_item.duration
                        )
                        db["clsb20_user_purchase_item"].insert(
                            user_id=user_id,
                            purchase_id=product_purchase.clsb20_purchase_item.
                            id,
                            # times=product_purchase.clsb20_purchase_item.times,
                            day_end=day_end)
                        db["clsb20_purchase_renew_history"].insert(
                            user_id=user_id,
                            product_id=product_id,
                            date_do_renew=datetime.today())
                else:
                    change_time_first = db(db.clsb20_product_price_history.product_id == product_id)\
                            (db.clsb20_product_price_history.purchase_item == product_purchase.clsb20_purchase_item.id).select(orderby=db.clsb20_product_price_history.changing_time)

                    if len(change_time_first) > 0:
                        change_time_first = change_time_first.first()
                        rows = db(db.clsb_download_archieve.user_id == user_id)(db.clsb_download_archieve.product_id == product_id)\
                            (db.clsb_download_archieve.download_time >=  change_time_first.changing_time).select(db.clsb_download_archieve.status)
                        if len(rows) > 0:
                            pass
                        else:
                            if oldCBM:
                                new_fund -= total / 2
                            else:
                                new_fund -= total
                    else:
                        rows = db(
                            (db.clsb_download_archieve.user_id == user_id)
                            & (db.clsb_download_archieve.product_id ==
                               product_id) &
                            (db.clsb_download_archieve.status.like("Completed")
                             | db.clsb_download_archieve.status.like(
                                 "TestSuccess"))).select(
                                     db.clsb_download_archieve.status)
                        if len(rows) > 0:
                            pass
                        else:
                            if oldCBM:
                                new_fund -= total / 2
                            else:
                                new_fund -= total
        data_sum = transaction.encrypt(new_fund, username)
        db(db.clsb_user.username == username).update(fund=new_fund,
                                                     data_sum=data_sum)

        data = dict(record_id=user_id,
                    table_name='clsb_user',
                    key_unique='username')
        insert_to_log_temp(data)
        # url_update_fund = URL(host=DOMAIN_VDC, a='cbs20', c="sync2vdc", f="update_user_fund",
        #                       vars=dict(fund=new_fund, data_sum=data_sum, username=username))
        # print(url_update_fund)
        # urllib2.urlopen(url_update_fund)
        return CB_0000  # SUCCESS
    except:
        import traceback
        traceback.print_exc()
        # print "Error at pay() in modules/transaction.py: " + str(e) +" on line: "+str(sys.exc_traceback.tb_lineno)
        return str(sys.exc_traceback.tb_lineno)  # db_RQ_FAILD
Exemple #7
0
def pay_to_log_divide(user, product, classbook_device, isMedia, pay, end_buy=False):
    # if classbook_device and check_free_for_classbook(product['clsb_category']['id']):
    #     print('return1')
    #     return "True 1"
    if isMedia.lower() == 'false':
        if not check_free_for_classbook(product['clsb_category']['id']):
            downloaded = db(db.clsb_download_archieve.product_id == product['clsb_product']['id'])(db.clsb_download_archieve.status.like("Completed"))(db.clsb_download_archieve.user_id == user['id']).select()
            if len(downloaded) > 0:
                print('return2')
                return "True 2"
    """
    Mua cho thiet bi class book voi gia sach SGK se ko ghi log
    """
    import applications.cbs20.modules.transaction as transaction

    if isMedia.lower() == 'true':
        check_buy = db(db.clsb30_media_history.product_id == product['clsb_product']['id'])(db.clsb30_media_history.user_id == user['id']).select()
        print(check_buy)
        if len(check_buy) > 0:
            print('return3')
            return "True 3"
    else:
        check_buy = db(db.clsb30_product_history.product_id == product['clsb_product']['id'])(db.clsb30_product_history.user_id == user['id']).select()
        print(check_buy)
        if len(check_buy) > 0:
            print('return4')
            return "True 4"
    if not end_buy:
        user_cash = db(db.clsb_user.id == user['id']).select(db.clsb_user.fund, db.clsb_user.data_sum).as_list()
        user_cash = user_cash[0]['fund']
        new_fund = int(user_cash) - int(pay)
        if new_fund < 0:
            print('return5')
            return dict(error='Tiền trong tài khoản không đủ')
        print('tiench new_fund: ' + str(new_fund))
        data_sum = transaction.encrypt(new_fund, user['username'])
        db(db.clsb_user.username == user['username']).update(fund=new_fund, data_sum=data_sum)

        user_id = db(db.clsb_user.username == user['username']).select().first()['id']
        data = dict(record_id=user_id, table_name='clsb_user', key_unique='username')
        insert_to_log_temp(data)
        # url_update_fund = URL(host=DOMAIN_VDC, a='cbs20', c="sync2vdc", f="update_user_fund",
        #                       vars=dict(fund=new_fund, data_sum=data_sum, username=user['username']))
        # print(url_update_fund)
        # update_result = urllib2.urlopen(url_update_fund)
        # print(update_result.read())
    if isMedia.lower() == 'true':
        print("tiench insert media: " + str(isMedia))
        if len(db(db.clsb30_media_history.product_id == product['clsb_product']['id'])(db.clsb30_media_history.user_id == user['id']).select()) <= 0:
            media_insert = db.clsb30_media_history.insert(
                product_title=product['clsb_product']['product_title'],
                product_id=product['clsb_product']['id'],
                user_id=user['id'],
                category_id=product['clsb_category']['id'],
                product_price=pay
            )

            params = {'searchTxt': 'ND',
                  'clientIP': '',
                  'dserial': "",
                  'pcode': product['clsb_product']['product_code'],
                  'purchase_type': 'WEB_PAY',
                  'rom_version': "CLASSBOOK.APP",
                  'userID': user_id,
                  'price': int(pay),
                  'status': 'Completed'}
            log_20(params, True)

            db.clsb30_payment_log.insert(user_id=user_id, product_id=product['clsb_product']['id'],
                                         product_type='MEDIA', pay=int(pay))

            data = dict(record_id=str(media_insert), table_name='clsb30_media_history', key_unique='user_id.product_id')
            insert_to_log_temp(data)
            # url_sign = URL(host=DOMAIN_VDC, a='cbs20', c="sync2vdc", f="sign_buy_media", args=["Product",
            #                                                                                 product['clsb_product']['id'],
            #                                                                                 user['username'],
            #                                                                                 product['clsb_category']['id'],
            #                                                                                 pay])
            # print(url_sign)
            # urllib2.urlopen(url_sign)
    else:
        print("tiench insert product: " + str(isMedia))
        try:
            if len(db(db.clsb30_product_history.product_id == product['clsb_product']['id'])(db.clsb30_product_history.user_id == user['id']).select()) <= 0:
                product_insert = db.clsb30_product_history.insert(
                    product_title=product['clsb_product']['product_title'],
                    product_id=product['clsb_product']['id'],
                    user_id=user['id'],
                    category_id=product['clsb_category']['id'],
                    product_price=pay
                )
                params = {'searchTxt': 'ND',
                  'clientIP': '',
                  'dserial': "",
                  'pcode': product['clsb_product']['product_code'],
                  'purchase_type': 'WEB_PAY',
                  'rom_version': "CLASSBOOK.APP",
                  'userID': user_id,
                  'price': int(pay),
                  'status': 'Completed'}
                log_20(params, True)
                db.clsb30_payment_log.insert(user_id=user_id, product_id=product['clsb_product']['id'],
                                         product_type='PRODUCT', pay=int(pay))
                data = dict(record_id=str(product_insert), table_name='clsb30_product_history', key_unique='user_id.product_id')
                insert_to_log_temp(data)

                # url_sign = URL(host=DOMAIN_VDC, a='cbs20', c="sync2vdc", f="sign_buy_product", args=["Product",
                #                                                                                      product['clsb_product']['id'],
                #                                                                                      user['username'],
                #                                                                                      product['clsb_category']['id'],
                #                                                                                      pay])
                # print(url_sign)
                # urllib2.urlopen(url_sign)
        except Exception as err:
            print("Error: " + err)
            return dict(error=str(err))
    return "True final"
    def post(*args, **vas):
        """
            user_token
            username
            nl_function
            nl_version
            order_code
            total_amount
            payment_method,
        """
        if not len(args) == 1 or \
                (not args[0] == nl_function and not args[0] == nl_card_function):
            raise HTTP(400, "Function Error")
        else:
            function = args[0]

        if not "user_token" in vas or \
                not "user_name" in vas or not "version" in vas:
            raise HTTP(400, "Key Error")
        else:
            user_token = vas["user_token"]
            user_name = vas["user_name"]
            version = vas["version"]

        if (function == nl_function and not version == nl_version) or \
                (function == nl_card_function and not version == nl_card_version):
            raise HTTP(400, "Version Error")

        user_query = db((db[table_user].username == user_name)
                        & (db[table_user].user_token == user_token))
        user = user_query.select(db[table_user].lastLoginTime,
                                 db[table_user].email,
                                 db[table_user].phoneNumber,
                                 db[table_user].address,
                                 db[table_user].firstName,
                                 db[table_user].lastName, db[table_user].id)

        if len(user) == 0:
            raise HTTP(401)  # ValueError("Authentical Error")

        buyer_id = user[0].id
        buyer_email = user[0].email
        buyer_mobile = user[0].phoneNumber
        buyer_address = user[0].address
        buyer_fullname = "%s %s" % (user[0].firstName, user[0].lastName)

        if function == nl_function and version == nl_version:
            service = NganLuongCheckout(nl_merchant_id, nl_merchant_password,
                                        nl_receiver_email)
            if "token" in vas:
                nl_token = vas["token"]
                trans_token_count = db(
                    db.clsb_transaction.token == nl_token).count()
                if trans_token_count > 0:
                    raise HTTP(400, "Giao dịch đã tồn tại!")
                nl_data = service.get_transaction_detail(nl_token)
                if nl_data is not None:
                    error_code = nl_data["error_code"]
                    if not error_code == "00":
                        db(db.clsb_transaction.id ==
                           nl_data["order_code"]).update(status="FAIL",
                                                         token=error_code)
                        raise HTTP(400, error_code)
                    else:
                        try:
                            old_fund = db(db.clsb_user.id == buyer_id).select(
                                db.clsb_user.fund)[0].fund
                            if isinstance(old_fund, (int, long)):
                                new_fund = int(old_fund)
                                new_fund += int(nl_data["total_amount"])
                                data_sum = encrypt(new_fund, user_name)
                                db(db.clsb_user.id == buyer_id).update(
                                    fund=new_fund, data_sum=data_sum)
                            else:
                                return dict(error="Error fund")
                            order_code = nl_data["order_code"]
                            q = db(db.clsb_transaction.id == order_code)
                            payment_type = q.select().first()['payment_type']
                            amount = int(nl_data["total_amount"])
                            face_value = amount
                            real_value = amount
                            if payment_type == "VISA":
                                face_value = amount
                                real_value = amount * 0.97 - 5500
                            elif payment_type == "ATM_ONLINE":
                                face_value = amount
                                real_value = amount * 0.985 - 500
                            q.update(status="COMPLETE",
                                     amount=nl_data["total_amount"],
                                     token=nl_token,
                                     face_value=face_value,
                                     real_value=real_value,
                                     order_code=nl_data["order_code"],
                                     merchant_id=nl_data["transaction_id"])
                            return nl_data["total_amount"]
                        except Exception as ex:
                            raise HTTP(404, str(ex))
                else:
                    raise HTTP(400, "Undefine")
            elif "payment_method" in vas or "bank_code" in vas or \
                            "success_url" in vas or "cancel_url" in vas or \
                            "buyer_amount" in vas or "description" in vas:
                payment_method = vas["payment_method"]
                bank_code = vas["bank_code"]
                buyer_amount = vas["buyer_amount"]
                description = vas["description"]
                success_url = vas["success_url"]
                cancel_url = vas["cancel_url"]
                # print("nl: " + str(vas))
                if nl_minimum_cost > int(buyer_amount):
                    str_err = "Số tiền nạp ít nhất là %d VNĐ" % nl_minimum_cost
                    raise HTTP(400, str_err)

                mid = nl_merchant_id
                site = ""
                if "site" in vas:
                    site = vas['site']
                discount_code = ""
                if "discount_code" in vas:
                    discount_code = vas['discount_code']
                tid = db.clsb_transaction.insert(user_id=int(buyer_id),
                                                 merchant_account=mid,
                                                 amount=int(buyer_amount),
                                                 payment_type=payment_method,
                                                 description=description,
                                                 nl_version=version,
                                                 nl_function=function,
                                                 bank_code=bank_code,
                                                 site=site,
                                                 discount_code=discount_code)
                # if "purchase_type" in request.vars and request.vars.purchase_type != "":
                #     db.clsb30_elearning_transaction.insert(user_id=int(buyer_id),
                #                                            package_code=request.vars.package,
                #                                            purchase_type=request.vars.purchase_type,
                #                                            email_receiver=request.vars.email,
                #                                            pack_type=request.vars.pack_type,
                #                                            transaction_id=int(tid))
                db.commit()
                try:
                    nl_data = service.checkout(payment_method, bank_code,
                                               int(tid), int(buyer_amount),
                                               description, success_url,
                                               cancel_url, buyer_fullname,
                                               buyer_email, buyer_mobile,
                                               buyer_address)
                    if nl_data is not None:
                        error_code = nl_data["error_code"]
                        if not error_code == "00":
                            db(db.clsb_transaction.id == tid).update(
                                status="FAIL", token=error_code)
                            raise HTTP(400, error_code)
                        else:
                            return nl_data["checkout_url"]
                    else:
                        db(db.clsb_transaction.id == tid).update(status="FAIL")
                        raise HTTP(400, "Undefine")
                except Exception as ex:
                    db(db.clsb_transaction.id == tid).update(status="FAIL")
                    raise HTTP(400, str(ex))

        elif (function == nl_card_function and version == nl_card_version) and \
                ("pin_card" in vas or "card_serial" in vas or "type_card" in vas):
            pin_card = vas["pin_card"]
            card_serial = vas["card_serial"]
            type_card = vas["type_card"]
            site = ""
            if "site" in vas:
                site = vas['site']
            discount_code = ""
            if "discount_code" in vas:
                discount_code = vas['discount_code']
            card_service = MobiCard()
            tid = db.clsb_transaction.insert(user_id=int(buyer_id),
                                             merchant_account=nl_merchant_id,
                                             payment_type=type_card,
                                             nl_version=version,
                                             nl_function=function,
                                             card_serial=card_serial,
                                             card_pin=pin_card,
                                             site=site,
                                             discount_code=discount_code)
            # if "purchase_type" in request.vars and request.vars.purchase_type != "":
            #     db.clsb30_elearning_transaction.insert(user_id=int(buyer_id),
            #                                            package_code=request.vars.package,
            #                                            purchase_type=request.vars.purchase_type,
            #                                            email_receiver=request.vars.email,
            #                                            pack_type=request.vars.pack_type,
            #                                            transaction_id=int(tid))
            db.commit()
            nl_data = card_service.card_pay(pin_card, card_serial, type_card,
                                            int(tid), buyer_fullname,
                                            buyer_mobile, buyer_email)
            if nl_data is not None:
                # print(nl_data)
                error_code = nl_data["error_code"]
                #print(error_code)
                if error_code == "00":
                    try:
                        old_fund = db(
                            db.clsb_user.email == buyer_email).select(
                                db.clsb_user.fund)[0]['fund']
                        if isinstance(old_fund, (int, long)):
                            new_fund = old_fund + int(nl_data["card_amount"])
                            data_sum = encrypt(new_fund, user_name)
                            db(db.clsb_user.id == buyer_id).update(
                                fund=new_fund, data_sum=data_sum)
                        else:
                            raise HTTP(400, "Undefine")
                        db(db.clsb_transaction.id == tid).update(
                            status="COMPLETE",
                            amount=nl_data["amount"],
                            card_amount=nl_data["card_amount"],
                            face_value=nl_data["card_amount"],
                            real_value=nl_data["amount"],
                            merchant_id=nl_data["transaction_id"])
                        return nl_data["card_amount"]
                    except Exception as ex:
                        print(str(ex) + str(sys.exc_traceback.tb_lineno))
                        raise HTTP(404,
                                   str(ex) + str(sys.exc_traceback.tb_lineno))
                else:
                    try:
                        db(db.clsb_transaction.id == tid).update(
                            status="FAIL", token=error_code)
                        #print("error code " + error_code)
                        raise HTTP(300, error_code)
                    except Exception as ex:
                        print(str(ex) + str(sys.exc_traceback.tb_lineno))
                        raise HTTP(400,
                                   str(ex) + str(sys.exc_traceback.tb_lineno))

        raise HTTP(400, "Key Error")
    def post(*args, **vas):
        """
            user_token
            username
            nl_function
            nl_version
            order_code
            total_amount
            payment_method,
        """
        if not len(args) == 1 or \
           (not args[0] == nl_function and not args[0] == nl_card_function):
            raise HTTP(400, "Function Error")
        else:
            function = args[0]

        if not "user_token" in vas or \
                not "user_name" in vas or not "version" in vas:
            raise HTTP(400, "Key Error")
        else:
            user_token = vas["user_token"]
            user_name = vas["user_name"]
            version = vas["version"]

        if (function == nl_function and not version == nl_version) or \
           (function == nl_card_function and not version == nl_card_version):
            raise HTTP(400, "Version Error")

        user_query = db((db[table_user].username == user_name)
                        & (db[table_user].user_token == user_token))
        user = user_query.select(db[table_user].lastLoginTime,
                                 db[table_user].email,
                                 db[table_user].phoneNumber,
                                 db[table_user].address,
                                 db[table_user].firstName,
                                 db[table_user].lastName, db[table_user].id)

        if len(user) == 0 or user[0].lastLoginTime + TIME_OUT < datetime.now():
            raise HTTP(401)  # ValueError("Authentical Error")

        buyer_id = user[0].id
        buyer_email = user[0].email
        buyer_mobile = user[0].phoneNumber
        buyer_address = user[0].address
        buyer_fullname = "%s %s" % (user[0].firstName, user[0].lastName)

        if function == nl_function and version == nl_version:
            service = NganLuongCheckout(nl_merchant_id, nl_merchant_password,
                                        nl_receiver_email)
            if "token" in vas:
                nl_token = vas["token"]
                trans_token_count = db(
                    db.clsb_transaction.token == nl_token).count()
                if trans_token_count > 0:
                    raise HTTP(400, "Giao dịch đã tồn tại!")
                nl_data = service.get_transaction_detail(nl_token)
                if nl_data is not None:
                    error_code = nl_data["error_code"]
                    if not error_code == "00":
                        db(db.clsb_transaction.id ==
                           nl_data["order_code"]).update(status="FAIL",
                                                         token=error_code)
                        raise HTTP(400, error_code)
                    else:
                        try:
                            old_fund = db(db.clsb_user.id == buyer_id).select(
                                db.clsb_user.fund)[0].fund
                            if isinstance(old_fund, (int, long)):
                                new_fund = int(old_fund)
                                new_fund += int(nl_data["total_amount"])
                                data_sum = encrypt(new_fund, user_name)
                                db(db.clsb_user.id == buyer_id).update(
                                    fund=new_fund, data_sum=data_sum)
                                data = dict(record_id=buyer_id,
                                            table_name='clsb_user',
                                            key_unique='username')
                                insert_to_log_temp(data)
                            else:
                                raise HTTP(400, "Undefine")
                            order_code = nl_data["order_code"]
                            q = db(db.clsb_transaction.id == order_code)
                            q.update(status="COMPLETE",
                                     amount=nl_data["total_amount"],
                                     token=nl_token,
                                     order_code=nl_data["order_code"],
                                     merchant_id=nl_data["transaction_id"])
                            return nl_data["total_amount"]
                        except Exception as ex:
                            raise HTTP(400, str(ex))
                else:
                    raise HTTP(400, "Undefine")
            elif "payment_method" in vas or "bank_code" in vas or \
                 "success_url" in vas or "cancel_url" in vas or \
                 "buyer_amount" in vas or "description" in vas:
                payment_method = vas["payment_method"]
                bank_code = vas["bank_code"]
                buyer_amount = vas["buyer_amount"]
                description = vas["description"]
                success_url = vas["success_url"]
                cancel_url = vas["cancel_url"]
                #print("nl: " + str(vas))
                if nl_minimum_cost > int(buyer_amount):
                    str_err = "Số tiền nạp ít nhất là %d VNĐ" % nl_minimum_cost
                    raise HTTP(400, str_err)

                mid = nl_merchant_id
                tid = db.clsb_transaction.insert(user_id=int(buyer_id),
                                                 merchant_account=mid,
                                                 amount=int(buyer_amount),
                                                 payment_type=payment_method,
                                                 description=description,
                                                 nl_version=version,
                                                 nl_function=function,
                                                 bank_code=bank_code)
                db.commit()
                try:
                    nl_data = service.checkout(payment_method, bank_code,
                                               int(tid), int(buyer_amount),
                                               description, success_url,
                                               cancel_url, buyer_fullname,
                                               buyer_email, buyer_mobile,
                                               buyer_address)
                    if nl_data is not None:
                        error_code = nl_data["error_code"]
                        if not error_code == "00":
                            db(db.clsb_transaction.id == tid).update(
                                status="FAIL", token=error_code)
                            raise HTTP(400, error_code)
                        else:
                            return nl_data["checkout_url"]
                    else:
                        db(db.clsb_transaction.id == tid).update(status="FAIL")
                        raise HTTP(400, "Undefine")
                except Exception as ex:
                    db(db.clsb_transaction.id == tid).update(status="FAIL")
                    raise HTTP(400, str(ex))

        elif (function == nl_card_function and version == nl_card_version) and \
             ("pin_card" in vas or "card_serial" in vas or "type_card" in vas):
            pin_card = vas["pin_card"]
            card_serial = vas["card_serial"]
            type_card = vas["type_card"]

            card_service = MobiCard()
            tid = db.clsb_transaction.insert(user_id=int(buyer_id),
                                             merchant_account=nl_merchant_id,
                                             payment_type=type_card,
                                             nl_version=version,
                                             nl_function=function,
                                             card_serial=card_serial,
                                             card_pin=pin_card)
            db.commit()
            nl_data = card_service.card_pay(pin_card, card_serial, type_card,
                                            int(tid), buyer_fullname,
                                            buyer_mobile, buyer_email)
            if nl_data is not None:
                #print(nl_data)
                error_code = nl_data["error_code"]
                print(error_code)
                if error_code == "00":
                    try:
                        old_fund = db(db.clsb_user.id == buyer_id).select(
                            db.clsb_user.fund)[0].fund
                        if isinstance(old_fund, (int, long)):
                            new_fund = old_fund + int(nl_data["card_amount"])
                            data_sum = encrypt(new_fund, user_name)
                            db(db.clsb_user.id == buyer_id).update(
                                fund=new_fund, data_sum=data_sum)
                            data = dict(record_id=buyer_id,
                                        table_name='clsb_user',
                                        key_unique='username')
                            insert_to_log_temp(data)
                        else:
                            raise HTTP(400, "Undefine")
                        db(db.clsb_transaction.id == tid).update(
                            status="COMPLETE",
                            amount=nl_data["amount"],
                            card_amount=nl_data["card_amount"],
                            merchant_id=nl_data["transaction_id"])
                        return nl_data["card_amount"]
                    except Exception as ex:
                        print(str(ex) + str(sys.exc_traceback.tb_lineno))
                        raise HTTP(400,
                                   str(ex) + str(sys.exc_traceback.tb_lineno))
                else:
                    try:
                        db(db.clsb_transaction.id == tid).update(
                            status="FAIL", token=error_code)
                        print("error code " + error_code)
                        raise HTTP(300, error_code)
                    except Exception as ex:
                        print(str(ex) + str(sys.exc_traceback.tb_lineno))
                        raise HTTP(400,
                                   str(ex) + str(sys.exc_traceback.tb_lineno))

        raise HTTP(400, "Key Error")