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

333 lines
14 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 addbz_order(ns={}):
"""
生成订单 立即下单
userid : 用户id
`goods`'产品id',
`spec_id` '规格id',
`quantity`'数量',
`transname` '交易名称',
`providerid` '供应商id',
`order_status` '0:未支付1:已交付2:已关闭3:已取消4:后付费',
"""
sor = ns['sor']
userid = ns['userid']
orgid = ns['orgid']
try:
amountadll = 0
bz_ns = {}
bz_ns['id'] = uuid()
bz_ns['order_status'] = '0'
bz_ns['business_op'] = 'BUY'
bz_ns['userid'] = userid
bz_ns['customerid'] = orgid
bz_ns['source'] = '容器云'
bz_ns['order_date'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
bz_ns['autoreneworder'] = '1' if ns.get('autoRenewOrder') else '0'
if ns.get('specdataid'):
bz_ns['specdataid'] = ns['specdataid']
await sor.C('bz_order', bz_ns)
# 添加账户表
nss = {}
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')
nss['chargemode'] = 'prepay'
nss['servicename'] = 'k8s-gpu'
nss['chargeduration'] = ns.get('chargeduration')
nss['unit'] = ns.get('unit')
nss['resourcestarttime'] =datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
nss['resourceendtime'] = await cal_expire_time(chargeduration=nss['chargeduration'], unit=nss['unit'])
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 cal_expire_time(chargeduration=None, unit=None):
chargeduration = int(chargeduration)
# 当前时间
now = datetime.datetime.now()
if unit == 'hour' or unit == '小时':
expire_time = now + dateutil.relativedelta.relativedelta(hours=chargeduration)
elif unit == 'day' or unit == '天':
expire_time = now + dateutil.relativedelta.relativedelta(days=chargeduration)
elif unit == 'week' or unit == '星期':
expire_time = now + dateutil.relativedelta.relativedelta(weeks=chargeduration)
elif unit == 'month' or unit == '月':
expire_time = now + dateutil.relativedelta.relativedelta(months=chargeduration)
elif unit == 'quarter' or unit == '季度':
expire_time = now + dateutil.relativedelta.relativedelta(months=chargeduration * 3)
elif unit == 'year' or unit == '年':
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']
if ns:
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:
# 需要加事务
order_goods_id = None
customer_goods_id = None
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:
order_goods_id = j['id']
# 计算过期时间
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']})
nss = {}
nss['id'] = uuid()
customer_goods_id = nss['id']
# 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)
return {'status': True, 'msg': '支付成功', 'order_goods_id': order_goods_id, 'customer_goods_id': customer_goods_id}
except Exception as error:
return {
'status': False,
'msg': '%s' % str(error)
}
else:
return {'status': False, 'msg': '参数错误'}
async def create_cpcc_instance(ns={}):
if ns.get('userid'):
userid = ns.get('userid')
else:
userid = await get_user()
ns['userid'] = userid
db = DBPools()
async with db.sqlorContext('kboss') as sor:
# 获取用户orgid
orgid_li = await sor.R('users', {'id': userid})
orgid = orgid_li[0]['orgid']
# 比对账户余额和账单金额
balance_yuan = await getCustomerBalance(sor, orgid)
print('%s orgid: %s, 余额为: %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), orgid, balance_yuan))
print('将要扣除的金额: %s' % ns['amount'])
if not balance_yuan:
print('%s 用户%s 余额为空' % (time.strftime('%Y-%m-%d %H:%M:%S'), orgid))
return {
'status': False,
'msg': '余额不足, 请及时充值'
}
if balance_yuan < float(ns['amount']):
print('%s 用户%s 余额不足' % (time.strftime('%Y-%m-%d %H:%M:%S'), orgid))
return {
'status': False,
'msg': '余额不足, 请及时充值'
}
providerid = ns.get('providerid')
productid = ns.get('productid')
# 创建实例前直接扣费
addbz_order_ns = {
'sor': sor,
"userid": userid,
"orgid": orgid,
"productid": productid,
"quantity": "1",
"discount": 1,
"providerid": providerid,
"list_price": ns['amount'],
"amount": ns['amount'],
'autoreneworder': '1' if ns.get('autoRenewOrder') else '0',
'chargeduration': ns.get('duration'),
'unit': ns.get('duration_unit')
}
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,
'providerid': providerid
}
affirmbz_order_res = await affirmbz_order(affirmbz_order_ns)
if not affirmbz_order_res['status']:
await sor.rollback()
return {
'status': False,
'msg': '支付错误, 请联系售后 %s' % str(affirmbz_order_res)
}
order_goods_id = affirmbz_order_res['order_goods_id']
customer_goods_id = affirmbz_order_res['customer_goods_id']
try:
domain_url = ns.get('domain_url')
if ('https://www.kaiyuancloud.cn/dev' in domain_url) or ('localhost' in domain_url):
base_url = 'https://www.kaiyuancloud.cn/dev'
elif 'https://www.kaiyuancloud.cn' in domain_url:
base_url = 'https://www.kaiyuancloud.cn'
else:
base_url = domain_url.split('://')[0] + '://' + domain_url.split('://')[1].split('/')[0]
# 判断库存是否充足
stock_url = base_url + '/cpcc/cpcbuy/determine_accommodat.dspy'
cpcid_li = await sor.R('cpccluster', {'id': ns.get('clusterid')})
cpcid = cpcid_li[0]['cpcid']
product_info_li = await sor.R('product', {'id': productid})
product_spec = json.loads(product_info_li[0]['spec_note'])
payload = {
'cpcid': cpcid,
'clusterid': ns.get('clusterid'),
'resources': {'aa': product_spec}
}
async with aiohttp_client.request(
method='POST',
url=stock_url,
json=payload) as res:
data_stock = await res.json()
if data_stock.get('data'):
await sor.rollback()
return {
'status': False,
'msg': '库存不足'
}
create_instance_url = base_url + '/cpcc/cpcpodyaml/new_cpcpodyaml.dspy'
create_payload = {
"userid": ns.get("userid"),
"clusterid": ns.get("clusterid"),
"source_name": ns.get("source_name"),
"source_authuser": ns.get("source_authuser"),
"source_authpasswd": ns.get("source_authpasswd"),
"source_podengine": ns.get("source_podengine"),
"source_replicasetnum": ns.get("source_replicasetnum"),
"instance_type": ns.get("instance_type"),
"pod_imagepath": ns.get("pod_imagepath"),
"source_memrate": ns.get("source_memrate"),
"source_cpurate": ns.get("source_cpurate"),
"source_selflabel": ns.get("source_selflabel"),
"source_gpu": ns.get("source_gpu"),
"source_portmode": ns.get("source_portmode"),
"source_restartpolicy": ns.get("source_restartpolicy"),
"source_apiport": ns.get("source_apiport"),
"source_insideport": ns.get("source_insideport"),
"source_outsideport": ns.get("source_outsideport"),
"source_mountpath": ns.get("source_mountpath"),
"source_storagelimits": ns.get("source_storagelimits"),
"source_nodeselector": ns.get("source_nodeselector"),
"orgid": orgid,
"cpu_model": ns.get("cpu_model"),
"gpu_model": ns.get("gpu_model"),
"disk_sys_limit": ns.get("disk_sys_limit"),
}
async with aiohttp_client.request(
method='POST',
url=create_instance_url,
json=create_payload) as res:
data_create = await res.json()
if data_create.get('status'):
k8s_data_ns = {
'id': data_create['data']['id'],
'productid': ns.get('productid'),
'sourceid': data_create['data']['id'],
'spec_data': json.dumps(data_create['data'])
}
await sor.C('specificdata', k8s_data_ns)
await sor.U('order_goods', {'id': order_goods_id, 'spec_id': k8s_data_ns['id'], 'resourceids': k8s_data_ns['id']})
await sor.U('customer_goods', {'id': customer_goods_id, 'specdataid': k8s_data_ns['id'], 'resourceid': k8s_data_ns['id']})
return {
'status': True,
'msg': '创建实例成功'
}
else:
await sor.rollback()
return {
'status': False,
'msg': 'create instance failed, %s' % str(data_create)
}
except Exception 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 has failed, %s' % str(e)
}
ret = await create_cpcc_instance(params_kw)
return ret