836 lines
38 KiB
Plaintext
836 lines
38 KiB
Plaintext
async def get_discount_or_price(ns={}):
|
||
# ns = {
|
||
# 'orgname': '北京首都在线科技股份有限公司',
|
||
# 'productname': '云硬盘',
|
||
# 'user_orgid': 'gKG8UaYPjA_29K7puzaTM'
|
||
# }
|
||
db = DBPools()
|
||
async with db.sqlorContext('kboss') as sor:
|
||
try:
|
||
# 查找供应商id
|
||
providerid_li = await sor.R('organization', {'orgname': ns.get('orgname'), 'del_flg': '0'})
|
||
if providerid_li:
|
||
providerid = providerid_li[0]['id']
|
||
provider_parentid = providerid_li[0]['parentid']
|
||
else:
|
||
return {
|
||
'status': False,
|
||
'msg': '没有找到指定名字的供应商'
|
||
}
|
||
# 查找产品id
|
||
productid_li = await sor.R('product', {'providerid': providerid, 'name': ns.get('productname')})
|
||
if productid_li:
|
||
productid = productid_li[0]['id']
|
||
else:
|
||
return {
|
||
'status': False,
|
||
'msg': '没有找到provider: %s对应的产品' % providerid
|
||
}
|
||
# 查找用户id, orgid, parentid
|
||
if ns.get('user_orgid'):
|
||
user_orgid = ns.get('user_orgid')
|
||
else:
|
||
user_orgid = (await sor.R('users', {'id': await get_user(), 'del_flg': '0'}))[0]['orgid']
|
||
user_parentid_li = await sor.R('organization', {'id': user_orgid, 'del_flg': '0'})
|
||
if user_parentid_li:
|
||
user_parentid = user_parentid_li[0]['parentid']
|
||
else:
|
||
return {
|
||
'status': False,
|
||
'msg': '没有找到对应用户的机构'
|
||
}
|
||
# 查找供应商和所属机构得协议
|
||
init_protocol_li = await sor.R('saleprotocol', {'offer_orgid': providerid, 'bid_orgid': provider_parentid, 'del_flg': '0'})
|
||
if init_protocol_li:
|
||
init_protocol = init_protocol_li[0]['salemode']
|
||
init_protocolid = init_protocol_li[0]['id']
|
||
origin_zi_search_li = await sor.R('product_salemode',
|
||
{'protocolid': init_protocolid, 'providerid': providerid, 'productid': productid, 'del_flg': '0'})
|
||
if init_protocol == '2':
|
||
origin_price = origin_zi_search_li[0]['price']
|
||
else:
|
||
origin_price = origin_zi_search_li[0]['discount']
|
||
else:
|
||
return {
|
||
'status': False,
|
||
'msg': '没有找到供应商: %s和用户所在机构: %s的协议' % (providerid, user_parentid)
|
||
}
|
||
if init_protocol == '2':
|
||
real_price = 1000000000000.0
|
||
person_price_sql = """select * from saleprotocol where offer_orgid = '%s' and bid_orgid = '%s' and
|
||
salemode = '2' and del_flg = '0' and CURRENT_DATE <= end_date and
|
||
CURRENT_DATE >= start_date""" % (user_parentid, user_orgid)
|
||
tongyi_price_sql = """select * from saleprotocol where offer_orgid = '%s' and bid_orgid = '*' and
|
||
salemode = '2' and del_flg = '0' and CURRENT_DATE <= end_date and
|
||
CURRENT_DATE >= start_date""" % user_parentid
|
||
for sql_detail in [person_price_sql, tongyi_price_sql]:
|
||
person_price_li = await sor.sqlExe(sql_detail, {})
|
||
for person_price in person_price_li:
|
||
protocolid = person_price['id']
|
||
xieyi_zi_search_li = await sor.R('product_salemode', {'protocolid': protocolid, 'providerid': providerid, 'del_flg': '0'})
|
||
for xieyi_zi in xieyi_zi_search_li:
|
||
provider_zi_id = xieyi_zi['providerid']
|
||
zi_price = xieyi_zi['price']
|
||
zi_productid = xieyi_zi['productid']
|
||
if provider_zi_id == providerid and zi_productid == productid:
|
||
# 判断产品是否存在 有可能在产品表已经删除
|
||
prd_res_exists_li = await sor.R('product', {'id': xieyi_zi['productid'], 'del_flg': '0'})
|
||
if not prd_res_exists_li:
|
||
continue
|
||
real_price = float(zi_price)
|
||
break
|
||
if real_price != 1000000000000.0:
|
||
break
|
||
if real_price == 1000000000000.0:
|
||
return {'status': False, 'msg': '没有找到产品价格'}
|
||
else:
|
||
return {'status': True, 'price': real_price, 'productid': productid, 'origin_price': origin_price}
|
||
|
||
# 如果签属的协议是折扣
|
||
if init_protocol == '0':
|
||
# 查找对应的产品id
|
||
if ns.get('prefix'):
|
||
productid_li = await sor.R('product', {'providerid': ns.get('providerid'), 'providerpid': ns.get('prefix') + '_' + ns.get('servicetype'), 'del_flg': '0'})
|
||
if productid_li:
|
||
productid_soure = productid_li[0]['id']
|
||
else:
|
||
return {'discount': 1.0}
|
||
else:
|
||
productid_soure = ns.get('productid')
|
||
|
||
real_discount = 1.0
|
||
person_discount_sql = """select * from saleprotocol where offer_orgid = '%s' and bid_orgid = '%s' and
|
||
salemode = '0' and del_flg = '0' and CURRENT_DATE <= end_date and
|
||
CURRENT_DATE >= start_date""" % (user_parentid, user_orgid)
|
||
tongyi_discount_sql = """select * from saleprotocol where offer_orgid = '%s' and bid_orgid = '*' and
|
||
salemode = '0' and del_flg = '0' and CURRENT_DATE <= end_date and
|
||
CURRENT_DATE >= start_date""" % user_parentid
|
||
# 没有个人配置 获取产品统一配置折扣
|
||
for sql_detail in [person_discount_sql, tongyi_discount_sql]:
|
||
person_discount_li = await sor.sqlExe(sql_detail, {})
|
||
for person_discount in person_discount_li:
|
||
protocolid = person_discount['id']
|
||
xieyi_zi_search_li = await sor.R('product_salemode', {'protocolid': protocolid, 'del_flg': '0'})
|
||
for xieyi_zi in xieyi_zi_search_li:
|
||
provider_zi_id = xieyi_zi['providerid']
|
||
zi_discount = xieyi_zi['discount']
|
||
zi_productid = xieyi_zi['productid']
|
||
if provider_zi_id == ns.get('providerid') and zi_productid == productid_soure:
|
||
# 判断产品是否存在 有可能在产品表已经删除
|
||
prd_res_exists_li = await sor.R('product', {'id': xieyi_zi['productid'], 'del_flg': '0'})
|
||
if not prd_res_exists_li:
|
||
continue
|
||
real_discount = float(zi_discount)
|
||
break
|
||
if real_discount != 1.0:
|
||
break
|
||
return {'status': True, 'discount': real_discount, 'productid': productid, 'origin_discount': origin_price}
|
||
if init_protocol == '2':
|
||
pass
|
||
except Exception as e:
|
||
return {'status': False, 'discount_price': 1.0, 'error_msg': str(e)}
|
||
|
||
async def get_eip_price(ns={}):
|
||
'''
|
||
获取弹性ip价格
|
||
:return:
|
||
'''
|
||
# ns = {
|
||
# 'user_orgid': 'gKG8UaYPjA_29K7puzaTM',
|
||
# "duration": "1",
|
||
# # "isMounth": "1",
|
||
# # "size": "1",
|
||
# # "siteId": "e5aa47be-da46-11ec-bad2-defff767b3b5",
|
||
# # "bandwidthConfIdStr": "10289",
|
||
# "qos": "2",
|
||
# # "isToMonth": "0",
|
||
# # "requestId": "6bca6bbd-xxxx-4xxx-xxxx-xxxxxxxxxxx1"
|
||
# }
|
||
import aiohttp
|
||
CCS_URL = 'http://cdsapi.capitalonline.net/gcw'
|
||
action = "GetEipPrice"
|
||
method = "GET"
|
||
param = {
|
||
"duration": ns.get('duration'),
|
||
"isMounth": ns.get('isMounth'),
|
||
"size": ns.get('size'),
|
||
"siteId": ns.get('siteId'),
|
||
"bandwidthConfIdStr": ns.get('bandwidthConfIdStr'),
|
||
"qos": ns.get('qos'),
|
||
"isToMonth": ns.get('isToMonth'),
|
||
"requestId": "6bca6bbd-1000-4x10-4xx1-1xxxxxxxxxx1"
|
||
}
|
||
nss = {
|
||
'orgname': '北京首都在线科技股份有限公司',
|
||
'user_orgid': ns.get('user_orgid'),
|
||
'productname': '宽带'
|
||
}
|
||
bandwidth_price_dic = await get_discount_or_price(nss)
|
||
if bandwidth_price_dic['status']:
|
||
bandwidth_price = float(bandwidth_price_dic['price']) * int(ns.get('duration')) * int(ns.get('qos'))
|
||
bandwidth_productid = bandwidth_price_dic.get('productid')
|
||
else:
|
||
return {
|
||
'status': False,
|
||
'msg': '无法获取配置的宽带价格 %s' % bandwidth_price_dic.get('msg')
|
||
}
|
||
nss['productname'] = '弹性IP'
|
||
eip_price_dic = await get_discount_or_price(nss)
|
||
if eip_price_dic['status']:
|
||
eip_price = float(eip_price_dic['price']) * int(ns.get('duration'))
|
||
eip_productid = eip_price_dic.get('productid')
|
||
else:
|
||
return {
|
||
'status': False,
|
||
'msg': '无法获取配置的弹性IP价格 %s' % eip_price_dic.get('msg')
|
||
}
|
||
if eip_price < 10:
|
||
price_unit = '/天'
|
||
else:
|
||
price_unit = "/%s个月" % ns.get('duration')
|
||
return {
|
||
"status": True,
|
||
"data": {
|
||
"bandwidth_price": {
|
||
"config_name": "bandwidth",
|
||
"cycle": price_unit,
|
||
"end_time": "",
|
||
"peak_qos_list": "[]",
|
||
"price": bandwidth_price,
|
||
"sale_price_unit": float(bandwidth_price_dic['price']),
|
||
"price_str": "%s" % bandwidth_price,
|
||
"sign": "¥",
|
||
"productid": bandwidth_productid,
|
||
'orgin': bandwidth_price_dic['origin_price']
|
||
},
|
||
"eip_price": {
|
||
"config_name": "eip",
|
||
"cycle": price_unit,
|
||
"end_time": "",
|
||
"peak_qos_list": "",
|
||
"price": eip_price,
|
||
"sale_price_unit": float(eip_price_dic['price']),
|
||
"price_str": "%s" % eip_price,
|
||
"sign": "¥",
|
||
"productid": eip_productid,
|
||
'orgin': eip_price_dic['origin_price']
|
||
},
|
||
"total_price": {
|
||
"cycle": price_unit,
|
||
"end_time": "",
|
||
"peak_qos_list": "",
|
||
"price": bandwidth_price + eip_price,
|
||
"price_str": "%s" % (bandwidth_price + eip_price),
|
||
"sign": "¥"
|
||
}
|
||
},
|
||
"msg": ""
|
||
}
|
||
# url = get_signature(action, method, CCS_URL, param=param)
|
||
# async with aiohttp.ClientSession() as session:
|
||
# async with session.request(method, url) as response:
|
||
# resp = await response.text()
|
||
# result = json.loads(resp)
|
||
# if result['Code'] == 'Success':
|
||
# result['status'] = True
|
||
# result.pop('Code')
|
||
# result['data'] = result.pop('Data')
|
||
# result['msg'] = result.pop('Message')
|
||
# else:
|
||
# result['status'] = False
|
||
# result['msg'] = result.pop('Message')
|
||
# return result
|
||
|
||
async def get_ecs_price(ns={}):
|
||
# ns = {
|
||
# 'user_orgid': 'gKG8UaYPjA_29K7puzaTM', # new
|
||
# # 'user_orgid': 'Oz80lKmjotfWYsMILloMb', # new
|
||
# "IsToMonth": 0,
|
||
# "AvailableZoneCode": "CN_Qingyang_A",
|
||
# "EcsFamilyName": "推理型智算云主机igch.c8.nr4",
|
||
# "Cpu": 16,
|
||
# "Ram": 64,
|
||
# "Gpu": 1,
|
||
# # "EcsFamilyName": "CPU计算型C8",
|
||
# # "Cpu": 4,
|
||
# # "Ram": 8,
|
||
# # "Gpu": 0,
|
||
#
|
||
# "BillingMethod": "1",
|
||
# "Duration": 2,
|
||
# "SystemDiskInfo": {
|
||
# "DiskFeature": "ssd",
|
||
# "Size": 40
|
||
# },
|
||
# "Number": 1,
|
||
# "DataDiskInfo": [
|
||
# {
|
||
# "DiskFeature": "ssd",
|
||
# "Size": 24
|
||
# },
|
||
# {
|
||
# "DiskFeature": "ssd",
|
||
# "Size": 32
|
||
# }
|
||
# ]
|
||
# }
|
||
import aiohttp
|
||
"""
|
||
获取云服务器价格
|
||
"""
|
||
ecs_url = 'http://api.capitalonline.net/ecs/v1'
|
||
action = "DescribePrice"
|
||
method = "POST"
|
||
param = {}
|
||
if ns.get('IsToMonth') == 0 or ns.get('IsToMonth') == '0':
|
||
istomonth = 0
|
||
else:
|
||
istomonth = 1
|
||
|
||
if ns.get('BillingMethod') == 0 or ns.get('BillingMethod') == '0':
|
||
time_unit = '天'
|
||
else:
|
||
time_unit = '个月'
|
||
|
||
systemdiskinfo = ns.get('SystemDiskInfo')
|
||
if isinstance(systemdiskinfo, str):
|
||
systemdiskinfo = json.loads(systemdiskinfo)
|
||
|
||
datadiskinfo = ns.get('DataDiskInfo')
|
||
if datadiskinfo:
|
||
if isinstance(datadiskinfo, str):
|
||
datadiskinfo = json.loads(datadiskinfo)
|
||
|
||
db = DBPools()
|
||
async with db.sqlorContext('kboss') as sor:
|
||
# 查找供应商id
|
||
providerid_li = await sor.R('organization', {'orgname': '北京首都在线科技股份有限公司', 'del_flg': '0'})
|
||
if providerid_li:
|
||
providerid = providerid_li[0]['id']
|
||
provider_parentid = providerid_li[0]['parentid']
|
||
else:
|
||
return {
|
||
'status': False,
|
||
'msg': '没有找到指定名字的供应商'
|
||
}
|
||
exist_prducts = await sor.R('product', {'providerid': providerid, 'name': ns['EcsFamilyName'], 'del_flg': '0'})
|
||
if exist_prducts:
|
||
productid = None
|
||
for exist_prduct in exist_prducts:
|
||
spec_notes = json.loads(exist_prduct['spec_note'])
|
||
spec_dic = {}
|
||
for note in spec_notes:
|
||
spec_dic.update({note['configName']: note['value']})
|
||
if str(ns['Cpu']) == spec_dic['CPU'] and str(ns['Ram']) == spec_dic['内存']:
|
||
productid = exist_prduct['id']
|
||
nss = {
|
||
'orgname': '北京首都在线科技股份有限公司',
|
||
'user_orgid': ns.get('user_orgid'),
|
||
'productname': ns['EcsFamilyName']
|
||
}
|
||
ecs_price_dic = await get_discount_or_price(nss)
|
||
if ecs_price_dic['status']:
|
||
ecs_productid = ecs_price_dic['productid']
|
||
ecs_price = float(ecs_price_dic['price']) * int(ns.get('Duration'))
|
||
else:
|
||
return {
|
||
'status': False,
|
||
'msg': '无法获取配置的ecs价格 %s' % ecs_price_dic.get('msg')
|
||
}
|
||
nss['productname'] = '云硬盘'
|
||
disk_price_dic = await get_discount_or_price(nss)
|
||
print('disk_price_dic', disk_price_dic)
|
||
if disk_price_dic['status']:
|
||
disk_productid = disk_price_dic['productid']
|
||
disk_price = float(disk_price_dic['price']) * int(ns.get('Duration'))
|
||
else:
|
||
return {
|
||
'status': False,
|
||
'msg': '无法获取配置的云硬盘价格 %s' % disk_price_dic.get('msg')
|
||
}
|
||
datadisk_total = sum([int(datadisk['Size']) for datadisk in datadiskinfo])
|
||
disk_total = int(systemdiskinfo['Size']) + int(datadisk_total)
|
||
return {
|
||
"RequestId": "7eedccd5-4c14-43a9-9afb-ef3a66dc1af0",
|
||
"status": True,
|
||
"data": {
|
||
"PriceUnit": "%s%s" % (ns.get('Duration'), time_unit),
|
||
"PriceSymbol": "¥",
|
||
"TotalPrice": float(ecs_price) + (float(disk_price) * disk_total),
|
||
"EcsPrice": ecs_price,
|
||
'price_detail': [
|
||
{
|
||
'config_name': 'disk',
|
||
'productid': disk_productid,
|
||
'price': float(disk_price) * disk_total,
|
||
'orgin': disk_price_dic['origin_price'],
|
||
'sale_price_unit': float(disk_price_dic['price'])
|
||
},
|
||
{
|
||
'config_name': 'ecs',
|
||
'productid': ecs_productid,
|
||
'price': ecs_price,
|
||
'orgin': ecs_price_dic['origin_price'],
|
||
'sale_price_unit': float(ecs_price_dic['price'])
|
||
}
|
||
]
|
||
},
|
||
"msg": "获取计费信息成功!"
|
||
}
|
||
# else:
|
||
# return {
|
||
# 'status': False,
|
||
# 'msg': '有产品名称, 没有对应配置'
|
||
# }
|
||
# else:
|
||
# return {
|
||
# 'status': False,
|
||
# 'msg': '没有找到对应产品'
|
||
# }
|
||
|
||
body = {
|
||
"AvailableZoneCode": ns.get("AvailableZoneCode"),
|
||
"EcsFamilyName": ns.get("EcsFamilyName") or '',
|
||
"Cpu": int(ns.get("Cpu")),
|
||
"Ram": int(ns.get("Ram")),
|
||
"Gpu": int(ns.get("Gpu")) if ns.get("Gpu") else 0,
|
||
"BillingMethod": ns.get('BillingMethod'),
|
||
"Duration": int(ns.get("Duration")) if ns.get("Duration") else 1,
|
||
"IsToMonth": istomonth,
|
||
"SystemDiskInfo": systemdiskinfo,
|
||
"Number": int(ns.get("Number")) if ns.get("Number") else 1,
|
||
"DataDiskInfo": datadiskinfo if datadiskinfo else [],
|
||
}
|
||
url = get_signature(action, method, ecs_url, param)
|
||
async with aiohttp.ClientSession() as session:
|
||
async with session.request(method, url, json=body) as response:
|
||
resp = await response.text()
|
||
result = json.loads(resp)
|
||
if 'Message' in result.keys():
|
||
key_word = 'Message'
|
||
else:
|
||
key_word = 'Msg'
|
||
if result['Code'] == 'Success':
|
||
result['status'] = True
|
||
result.pop('Code')
|
||
result['data'] = result.pop('Data')
|
||
result['msg'] = result.pop(key_word)
|
||
else:
|
||
result['status'] = False
|
||
result['msg'] = result.pop(key_word)
|
||
return result
|
||
|
||
|
||
async def cal_expire_time(chargeduration=None, unit=None):
|
||
chargeduration = int(chargeduration)
|
||
# 当前时间
|
||
now = datetime.datetime.now()
|
||
if unit == 'day':
|
||
expire_time = now + dateutil.relativedelta.relativedelta(days=chargeduration)
|
||
elif unit == 'week':
|
||
expire_time = now + dateutil.relativedelta.relativedelta(weeks=chargeduration)
|
||
elif unit == 'month':
|
||
expire_time = now + dateutil.relativedelta.relativedelta(months=chargeduration)
|
||
elif unit == 'quarter':
|
||
expire_time = now + dateutil.relativedelta.relativedelta(months=chargeduration * 3)
|
||
elif unit == 'year':
|
||
expire_time = now + dateutil.relativedelta.relativedelta(years=chargeduration)
|
||
else:
|
||
expire_time = None
|
||
if expire_time:
|
||
return str(expire_time)
|
||
else:
|
||
return None
|
||
|
||
async def affirmbz_order(ns={}):
|
||
"""确认支付"""
|
||
sor = ns['sor']
|
||
# history_price = None
|
||
# target_protocol_id = None
|
||
# # 查询产品说明是否是product_sync
|
||
# order_productid_providerid = await sor.R('order_goods', {'orderid': ns['orderid']})
|
||
# order_productid = order_productid_providerid[0]['productid']
|
||
# order_providerid = order_productid_providerid[0]['providerid']
|
||
# description = (await sor.R('product', {'id': order_productid}))[0]['description']
|
||
# if ns['providername'] == '北京首都在线科技股份有限公司':
|
||
# target_id = ns['providerid']
|
||
# if target_id:
|
||
# # 查询业主机构针对所有客户的普通协议
|
||
# protocolid = (await sor.R('saleprotocol', {'offer_orgid': 'mIWUHBeeDM8mwAFPIQ8pS', 'bid_orgid': '*', 'salemode': '2', 'del_flg': '0'}))[0]['id']
|
||
# # 在产品价格表中更新价格配置
|
||
# id_sql = """select id, price from product_salemode where protocolid = '%s' and providerid = '%s' and productid = '%s' order by price desc limit 1;""" % (protocolid, target_id, order_productid)
|
||
# id_find = (await sor.sqlExe(id_sql, {}))[0]['id']
|
||
# target_protocol_id = id_find
|
||
# history_price = (await sor.sqlExe(id_sql, {}))[0]['price']
|
||
# # 查询价格
|
||
# current_price = (await sor.R('bz_order', {'id': ns['orderid']}))[0]['amount']
|
||
# await sor.U('product_salemode', {'id': id_find, 'price': current_price})
|
||
|
||
orgid = await sor.R('bz_order', {'id': ns['orderid']})
|
||
date = await get_business_date(sor=None)
|
||
await sor.U('bz_order',{'id':ns['orderid'],'order_date': time.strftime('%Y-%m-%d %H:%M:%S')})
|
||
count = await getCustomerBalance(sor, orgid[0]['customerid'])
|
||
if count == None:
|
||
count = 0
|
||
if count - float(orgid[0]['amount']) < 0:
|
||
pricedifference = count - round(orgid[0]['amount'],2)
|
||
return {'status': False, 'msg': '账户余额不足','pricedifference': round(pricedifference,2)}
|
||
await order2bill(ns['orderid'], sor)
|
||
bills = await sor.R('bill', {'orderid': ns['orderid'], 'del_flg': '0'})
|
||
try:
|
||
# 需要加事务
|
||
for i in bills:
|
||
ba = BillAccounting(i)
|
||
r = await ba.accounting(sor)
|
||
dates = datetime.datetime.now()
|
||
await sor.U('bz_order', {'id': ns['orderid'], 'order_status': '1','create_at':dates})
|
||
await sor.U('bill', {'id': ns['orderid'], 'bill_state': '1'})
|
||
order_goods = await sor.R('order_goods', {'orderid': ns['orderid']})
|
||
for j in order_goods:
|
||
|
||
# 计算过期时间
|
||
chargeduration = j.get('chargeduration')
|
||
unit = j.get('unit')
|
||
if chargeduration and unit:
|
||
expire_time = await cal_expire_time(chargeduration=chargeduration, unit=unit)
|
||
else:
|
||
expire_time = None
|
||
|
||
product = await sor.R('product', {'id': j['productid']})
|
||
if len(product[0]['name']) < 6:
|
||
continue
|
||
nss = {}
|
||
nss['id'] = uuid()
|
||
# nss['id'] = UUID()
|
||
nss['providerrid'] = product[0]['providerid']
|
||
nss['productname'] = product[0]['name']
|
||
nss['productdesc'] = product[0]['description']
|
||
nss['customerid'] = orgid[0]['customerid']
|
||
nss['productid'] = product[0]['id']
|
||
nss['specdataid'] = j['spec_id']
|
||
nss['orderid'] = orgid[0]['id']
|
||
nss['start_date'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||
if expire_time:
|
||
nss['expire_date'] = expire_time
|
||
if ns.get('product_url'):
|
||
nss['product_url'] = ns.get('product_url')
|
||
await sor.C('customer_goods', nss)
|
||
# v = {}
|
||
# v['orderid'] = orgid[0]['id']
|
||
# v['customerid'] = orgid[0]['customerid']
|
||
# v['providerid'] = product[0]['providerid']
|
||
# v['productid'] = product[0]['id']
|
||
# v['quantity'] = j['quantity']
|
||
# await path_call('../pub/hpc_save_bill.dspy', v)
|
||
# await sor.U('product_salemode', {'id': target_protocol_id, 'price': history_price})
|
||
return {'status': True, 'msg': '支付成功'}
|
||
except Exception as error:
|
||
raise error
|
||
|
||
async def addbz_order(ns={}):
|
||
"""
|
||
生成订单 立即下单
|
||
userid : 用户id
|
||
`goods`:'产品id',
|
||
`spec_id`: '规格id',
|
||
`quantity`:'数量',
|
||
`transname` :'交易名称',
|
||
`providerid` : '供应商id',
|
||
`order_status` : '0:未支付,1:已交付;2:已关闭;3:已取消;4:后付费',
|
||
"""
|
||
sor = ns['sor']
|
||
chargeduration = ns['chargeduration']
|
||
unit = ns['unit']
|
||
orderid = ns.get('orderid')
|
||
total_amount = ns.get('total_amount')
|
||
try:
|
||
user = await sor.R('users', {'id': await get_user()})
|
||
orgid = await sor.R('organization', {'id': user[0]['orgid']})
|
||
amountadll = 0
|
||
if not orderid:
|
||
bz_ns = {}
|
||
# bz_ns['id'] = UUID()
|
||
bz_ns['id'] = uuid()
|
||
orderid = bz_ns['id']
|
||
bz_ns['order_status'] = '0'
|
||
bz_ns['business_op'] = 'BUY'
|
||
bz_ns['userid'] = await get_user()
|
||
bz_ns['customerid'] = orgid[0]['id']
|
||
bz_ns['order_date'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||
if ns.get('specdataid'):
|
||
bz_ns['specdataid'] = ns['specdataid']
|
||
await sor.C('bz_order', bz_ns)
|
||
# 添加账户表
|
||
nss = {}
|
||
nss['id'] = uuid()
|
||
# nss['id'] = UUID()
|
||
nss['orderid'] = orderid
|
||
nss['productid'] = ns.get('productid')
|
||
nss['providerid'] = ns.get('providerid')
|
||
nss['list_price'] = ns.get('list_price')
|
||
nss['discount'] = ns.get('discount')
|
||
nss['quantity'] = ns.get('quantity')
|
||
nss['price'] = ns.get('price')
|
||
nss['spec_id'] = ns.get('spec_id')
|
||
nss['unit'] = unit
|
||
nss['chargeduration'] = chargeduration
|
||
# if int(ns.get('quantity')) > 1:
|
||
# nss['amount'] = float(ns['amount']) * int(ns['quantity'])
|
||
# amountadll += nss['amount']
|
||
# else:
|
||
nss['amount'] = ns['amount']
|
||
amountadll += float(nss['amount'])
|
||
print('amountadll', amountadll)
|
||
await sor.C('order_goods', nss)
|
||
await sor.U('bz_order', {'id': orderid, 'amount': total_amount})
|
||
return {'status': True, 'msg': '添加成功', 'bz_id': orderid}
|
||
except Exception as error:
|
||
raise error
|
||
|
||
|
||
async def create_ecs(ns={}):
|
||
"""
|
||
创建云服务器
|
||
没有传递测试账号返回 'Code': 'Success', 'Msg': '下发创建云服务器任务:账户余额不足,账户余额=[0.00] 当前订单金额=[1.33]'
|
||
传递测试账号返回 CN_Hohhot_B {'Code': 'OrderError', 'Msg': '下发创建云服务器任务:测试项目不能在此站点使用!', 'Data': {}, 'RequestId': 'd8cf83c0-ac81-4735-8174-f9dc8a9ae113'
|
||
传递测试账号返回 CN_Qingyang_A {'Code': 'Success', 'Msg': '创建云服务器任务下发成功!', 'Data': {'EventId': 'd803af66-4028-11ef-bc71-928234ad6a6f', 'EcsIdSet': ['ins-jpyk8i1trba4nvp5']}, 'RequestId': '750f7bab-e1a0-48dc-afb2-cb3aa5be71b9'}
|
||
BillingMethod: 1 包年包月
|
||
|
||
{'Code': 'MaxEcsCountExceed', 'Msg': '当前类型云服务器最多可创建0台', 'Data': {}, 'RequestId': '98cdc84c-9a7c-40e9-a315-0e51ebdafead'}
|
||
{'RequestId': 'c06f6cdb-8287-4a4a-9230-4ddfe306b845', 'status': True, 'data': {'EventId': 'c8c0e80e-87ec-4293-8fd5-b77adb5e1f01', 'EcsIdSet': ['ins-vom49t1t6hox8bvh']}, 'msg': '创建云服务器任务下发成功!'}
|
||
"""
|
||
ns['DataDisk'] = ns['DataDisk'] if ns.get('DataDisk') else []
|
||
import aiohttp
|
||
server_name = ns.get('Name') if ns.get('Name') else time.strftime('%Y%m%d%H%M%S')
|
||
ns['Name'] = ns['user_orgid'] + '0_____0' + server_name
|
||
ecs_url = 'http://api.capitalonline.net/ecs/v1'
|
||
action = "CreateInstance"
|
||
method = "POST"
|
||
param = {}
|
||
body = {
|
||
"AvailableZoneCode": ns.get('AvailableZoneCode'),
|
||
"EcsFamilyName": ns.get('EcsFamilyName'),
|
||
"Cpu": ns['Cpu'],
|
||
"Ram": ns['Ram'],
|
||
"Gpu": ns['Gpu'],
|
||
"Number": ns['Number'],
|
||
"BillingMethod": str(ns['BillingMethod']) if str(ns.get('BillingMethod')) == '1' else '0',
|
||
"ImageId": ns.get('ImageId'),
|
||
"SystemDisk": json.loads(ns['SystemDisk']) if isinstance(ns['SystemDisk'], str) else ns['SystemDisk'],
|
||
"DataDisk": json.loads(ns['DataDisk']) if isinstance(ns['DataDisk'], str) else ns['DataDisk'],
|
||
"VpcInfo": json.loads(ns['VpcInfo']) if isinstance(ns['VpcInfo'], str) else ns['VpcInfo'],
|
||
"SubnetInfo": json.loads(ns['SubnetInfo']) if isinstance(ns['SubnetInfo'], str) else ns['SubnetInfo'],
|
||
"PubnetInfo": json.loads(ns['PubnetInfo']) if isinstance(ns.get('PubnetInfo'), str) else ns.get('PubnetInfo'),
|
||
"SecurityGroups": json.loads(ns['SecurityGroups']) if isinstance(ns['SecurityGroups'], str) else ns['SecurityGroups'],
|
||
"Name": ns.get('Name'),
|
||
"StartNumber": ns.get('StartNumber') if ns.get('StartNumber') else 1,
|
||
"Password": ns.get('Password'),
|
||
"Duration": ns['Duration'],
|
||
"IsToMonth": ns['IsToMonth'] if str(ns.get('IsToMonth')) == '1' else 0,
|
||
"IsAutoRenewal": ns['IsAutoRenewal'] if str(ns.get('IsAutoRenewal')) == '1' else 0
|
||
# "TestAccount": '按需调度接口开关机测试'
|
||
}
|
||
|
||
systemdisk = int(body['SystemDisk']['Size'])
|
||
datadisk = sum([int(i['Size']) for i in body['DataDisk']]) if body.get('DataDisk') else 0
|
||
disksize = systemdisk + datadisk
|
||
|
||
qos_num = body['PubnetInfo'][0]['Qos'] if body['PubnetInfo'] else 0
|
||
|
||
# 如果不是指定的服务器 联系售后创建
|
||
# if str(ns.get('Cpu')) != '16' or str(ns.get('Ram')) != '64' or ns.get('EcsFamilyName') != '推理型智算云主机igch.c8.nr4':
|
||
# return {
|
||
# 'status': False,
|
||
# 'msg': '[%s]对应产品服务资源紧张!请联系售后开通!' % ns.get('EcsFamilyName')
|
||
# }
|
||
# 查找本地配置是否有对应资源
|
||
db = DBPools()
|
||
async with db.sqlorContext('kboss') as sor:
|
||
providerid_li = await sor.R('organization', {'orgname': '北京首都在线科技股份有限公司', 'del_flg': '0'})
|
||
if providerid_li:
|
||
providerid = providerid_li[0]['id']
|
||
else:
|
||
return {
|
||
'status': False,
|
||
'msg': '[%s] 供应资源紧张!请联系售后开通!' % ns.get('EcsFamilyName')
|
||
}
|
||
exist_prducts = await sor.R('product', {'providerid': providerid, 'name': ns['EcsFamilyName'], 'del_flg': '0'})
|
||
if exist_prducts:
|
||
productid = None
|
||
for exist_prduct in exist_prducts:
|
||
spec_notes = json.loads(exist_prduct['spec_note'])
|
||
spec_dic = {}
|
||
for note in spec_notes:
|
||
spec_dic.update({note['configName']: note['value']})
|
||
if str(ns['Cpu']) == spec_dic['CPU'] and str(ns['Ram']) == spec_dic['内存']:
|
||
productid = exist_prduct['id']
|
||
if not productid:
|
||
return {
|
||
'status': False,
|
||
'msg': '[%s] 产品ID资源紧张!请联系售后开通!' % ns.get('EcsFamilyName')
|
||
}
|
||
else:
|
||
return {
|
||
'status': False,
|
||
'msg': '[%s] 产品资源DI紧张!请联系售后开通!' % ns.get('EcsFamilyName')
|
||
}
|
||
|
||
ns_get_price_dic = {
|
||
'user_orgid': ns['user_orgid'],
|
||
"IsToMonth": ns['IsToMonth'],
|
||
"AvailableZoneCode": ns['AvailableZoneCode'],
|
||
"EcsFamilyName": ns['EcsFamilyName'],
|
||
"Cpu": int(ns['Cpu']),
|
||
"Ram": int(ns['Ram']),
|
||
"Gpu": int(ns['Gpu']),
|
||
"BillingMethod": ns['BillingMethod'],
|
||
"Duration": int(ns['Duration']),
|
||
"SystemDiskInfo": ns['SystemDisk'],
|
||
"Number": int(ns['Number']),
|
||
"DataDiskInfo": ns['DataDisk']
|
||
}
|
||
price_ecs_dic = await get_ecs_price(ns_get_price_dic)
|
||
print('price_ecs_dic', price_ecs_dic)
|
||
if price_ecs_dic['status']:
|
||
total_ecs_amount = price_ecs_dic['data']['TotalPrice']
|
||
else:
|
||
return {
|
||
'status': False,
|
||
'msg': '获取价格失败'
|
||
}
|
||
if ns.get('PubnetInfo'):
|
||
pubnetinfo = json.loads(ns['PubnetInfo']) if isinstance(ns['PubnetInfo'], str) else ns['PubnetInfo']
|
||
ns_eip = {
|
||
'user_orgid': ns['user_orgid'],
|
||
"duration": ns['Duration'],
|
||
"qos": pubnetinfo[0]['Qos']
|
||
}
|
||
price_eip_dic = await get_eip_price(ns_eip)
|
||
print('price_eip_dic', price_eip_dic)
|
||
if price_eip_dic['status']:
|
||
total_eip_amount = price_eip_dic['data']['total_price']['price']
|
||
price_ecs_dic['data']['price_detail'].append(price_eip_dic['data']['bandwidth_price'])
|
||
price_ecs_dic['data']['price_detail'].append(price_eip_dic['data']['eip_price'])
|
||
else:
|
||
return {
|
||
'status': False,
|
||
'msg': '获取EIP价格失败'
|
||
}
|
||
else:
|
||
total_eip_amount = 0
|
||
total_amount = round(float(total_ecs_amount) + float(total_eip_amount), 3)
|
||
|
||
# 比对账户余额和账单金额
|
||
# 9326.0326
|
||
balance_yuan = await getCustomerBalance(sor, ns['user_orgid'])
|
||
print('%s orgid: %s, 余额为: %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), ns['user_orgid'], balance_yuan))
|
||
print('将要扣除的金额: %s' % total_amount)
|
||
if not balance_yuan:
|
||
print('%s 用户%s 余额为空' % (time.strftime('%Y-%m-%d %H:%M:%S'), ns['user_orgid']))
|
||
return {
|
||
'status': False,
|
||
'msg': '余额不足, 请及时充值'
|
||
}
|
||
if balance_yuan < total_amount:
|
||
print('%s 用户%s 余额不足' % (time.strftime('%Y-%m-%d %H:%M:%S'), ns['user_orgid']))
|
||
return {
|
||
'status': False,
|
||
'msg': '余额不足, 请及时充值'
|
||
}
|
||
|
||
if body['BillingMethod'] == '0':
|
||
chargeduration = 1
|
||
unit = 'day'
|
||
else:
|
||
chargeduration = ns['Duration']
|
||
unit = 'month'
|
||
|
||
# 插入传入字典 用于续费
|
||
ns_spec = {
|
||
'id': uuid(),
|
||
'spec_data': json.dumps(ns)
|
||
}
|
||
await sor.C('specificdata', ns_spec)
|
||
|
||
orderid = None
|
||
for ser in price_ecs_dic['data']['price_detail']:
|
||
if ser['config_name'] == 'disk_unit':
|
||
continue
|
||
amount = ser['price']
|
||
productid = ser['productid']
|
||
if ser.get('config_name') and ser.get('config_name') == 'disk':
|
||
quantity = disksize
|
||
elif ser.get('config_name') and ser.get('config_name') == 'bandwidth':
|
||
quantity = qos_num
|
||
else:
|
||
quantity = '1'
|
||
|
||
addbz_order_ns = {
|
||
'sor': sor,
|
||
"userid": await get_user(), # TODO await get_user()
|
||
"productid": productid,
|
||
"quantity": quantity,
|
||
"providerid": providerid,
|
||
"list_price": ser['sale_price_unit'],
|
||
"price": ser['sale_price_unit'],
|
||
"amount": amount,
|
||
"chargeduration": chargeduration,
|
||
"unit": unit,
|
||
'specdataid': ns_spec['id'],
|
||
'spec_id': ns_spec['id'],
|
||
'orderid': orderid,
|
||
'total_amount': total_amount
|
||
}
|
||
addbz_order_res = await addbz_order(addbz_order_ns)
|
||
if addbz_order_res['status']:
|
||
orderid = addbz_order_res['bz_id']
|
||
else:
|
||
await sor.rollback()
|
||
return {
|
||
'status': False,
|
||
'msg': '账单错误,请联系售后'
|
||
}
|
||
affirmbz_order_ns = {
|
||
'sor': sor,
|
||
'orderid': orderid,
|
||
'providername': '北京首都在线科技股份有限公司',
|
||
'providerid': providerid
|
||
}
|
||
affirmbz_order_res = await affirmbz_order(affirmbz_order_ns)
|
||
if not affirmbz_order_res['status']:
|
||
await sor.rollback()
|
||
return {
|
||
'status': False,
|
||
'msg': '支付错误, 请联系售后'
|
||
}
|
||
return {'1': 2}
|
||
url = get_signature(action, method, ecs_url, param=param)
|
||
async with aiohttp.ClientSession() as session:
|
||
async with session.request(method, url, json=body) as response:
|
||
resp = await response.text()
|
||
result = json.loads(resp)
|
||
if result['Code'] == 'Success':
|
||
result['status'] = True
|
||
result.pop('Code')
|
||
result['data'] = result.pop('Data')
|
||
if result.get('Message'):
|
||
result['msg'] = result.pop('Message')
|
||
else:
|
||
result['msg'] = result.pop('Msg')
|
||
resourceid = result['data']['EcsIdSet'][0]
|
||
update_resource_sql = """UPDATE customer_goods set resourceid = '%s' WHERE orderid = '%s';""" \
|
||
% (resourceid, orderid)
|
||
await sor.sqlExe(update_resource_sql, {})
|
||
else:
|
||
result['status'] = False
|
||
if result.get('Message'):
|
||
result['msg'] = result.pop('Message')
|
||
else:
|
||
result['msg'] = result.pop('Msg')
|
||
await sor.rollback()
|
||
# raise ValueError('首都云服务器创建失败!, %s' % result)
|
||
return result
|
||
|
||
ret = await create_ecs(params_kw)
|
||
return ret
|
||
|