kboss/b/ucloud/create_uhost_instance.dspy
2025-07-16 14:27:17 +08:00

289 lines
12 KiB
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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']
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': date})
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:
product = await sor.R('product', {'id': j['productid']})
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")
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']
try:
user = await sor.R('users', {'id': await get_user()})
orgid = await sor.R('organization', {'id': user[0]['orgid']})
amountadll = 0
bz_ns = {}
# bz_ns['id'] = UUID()
bz_ns['id'] = uuid()
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")
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'] = bz_ns['id']
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('amount')
nss['spec_id'] = ns.get('spec_id')
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'])
await sor.C('order_goods', nss)
await sor.U('bz_order', {'id': bz_ns['id'], 'amount': amountadll})
return {'status': True, 'msg': '添加成功', 'bz_id': bz_ns['id']}
except Exception as error:
raise error
async def create_uhost_instance(ns={}):
import aiohttp
ns['amount'] = float(ns['amount'])
server_name = ns.get('Name') if ns.get('Name') else time.strftime('%Y%m%d%H%M%S')
ns['Name'] = ns['orgid'] + '0_____0' + server_name
db = DBPools()
async with db.sqlorContext('kboss') as sor:
# 比对账户余额和账单金额
# 11885.9626
balance_yuan = await getCustomerBalance(sor, ns['orgid'])
print('%s orgid: %s, 余额为: %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), ns['orgid'], balance_yuan))
print('将要扣除的金额: %s' % ns['amount'])
if not balance_yuan:
print('%s 用户%s 余额为空' % (time.strftime('%Y-%m-%d %H:%M:%S'), ns['orgid']))
return {
'status': False,
'msg': '余额不足, 请及时充值'
}
if balance_yuan < ns['amount']:
print('%s 用户%s 余额不足' % (time.strftime('%Y-%m-%d %H:%M:%S'), ns['orgid']))
return {
'status': False,
'msg': '余额不足, 请及时充值'
}
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['GpuType'], '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['GPU']) == spec_dic['GPU']:
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')
}
ucloud_user_li = await sor.R('ucloud_users', {'orgid': 'main_user', 'del_flg': '0'})
if ucloud_user_li:
uc_client = U_Client({
"project_id": ucloud_user_li[0]['projectid'],
"public_key": ucloud_user_li[0]['accesskey'],
"private_key": ucloud_user_li[0]['accesskeysecret'],
})
else:
return {
'status': False,
'msg': 'can not find u cloud user'
}
# 创建实例前直接扣费
addbz_order_ns = {
'sor': sor,
"userid": await get_user(),
"productid": productid,
"quantity": "1",
"providerid": providerid,
"list_price": ns['amount'],
"amount": ns['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,
'Quantity': ns['Quantity']
}
affirmbz_order_res = await affirmbz_order(affirmbz_order_ns)
if not affirmbz_order_res['status']:
await sor.rollback()
return {
'status': False,
'msg': '支付错误, 请联系售后'
}
try:
Disks = ns.get('Disks')
NetworkInterface = ns.get('NetworkInterface')
resp = uc_client.uhost().create_uhost_instance({
"Region": ns.get('Region'),
"Zone": ns.get('Zone'),
"ImageId": ns.get('ImageId'),
"LoginMode": ns.get('LoginMode'),
"Password": ns.get('Password'),
"Name": ns.get('Name'),
"Tag": "Default",
"ChargeType": ns.get('ChargeType'),
"Quantity": int(ns.get('Quantity')) if ns.get('Quantity') else 1,
"CPU": ns['CPU'],
"Memory": ns['Memory'],
"GpuType": ns.get('GpuType'),
"GPU": ns['GPU'],
"NetCapability": ns.get('NetCapability'),
"HotplugFeature": False,
"MachineType": ns.get('MachineType'),
'SecurityGroupId': ns.get('SecurityGroupId'),
'MinimalCpuPlatform': ns.get('MinimalCpuPlatform'),
"MaxCount": ns['MaxCount'] if ns.get('MaxCount') else 1,
"Disks": json.loads(Disks) if isinstance(Disks, str) else Disks,
"NetworkInterface": json.loads(NetworkInterface) if isinstance(NetworkInterface, str) else NetworkInterface
})
if not resp.get('UHostIds'):
await sor.rollback()
return {
'status': False,
'msg': 'create instance price failed',
'data': resp
}
return {
'status': True,
'msg': 'create instance price success',
'data': resp
}
except exc.UCloudException as e:
await sor.rollback()
if 'Lack of balance' in str(e):
return {
'status': False,
'msg': '余额不足, 请及时充值'
}
elif 'Resource not existeduimage' in str(e):
return {
'status': False,
'msg': '镜像不存在/不匹配'
}
elif 'Resource not enough' in str(e):
return {
'status': False,
'msg': '当前配置资源不足,请选择其他配置。'
}
elif 'Password Invalid' in str(e):
return {
'status': False,
'msg': '密码格式错误'
}
else:
return {
'status': False,
'msg': 'create instance failed, %s' % str(e)
}
ret = await create_uhost_instance(params_kw)
return ret