discount/wwwroot/api/init_free_customers.dspy

47 lines
1.7 KiB
Plaintext

"""Initialize discount_customer_bind for all users who don't have a bind record.
Each user is bound to their own org (users.orgid) as resellerid, bind_type='3'."""
userorgid = await get_userorgid()
if not userorgid:
return {'widgettype': 'Error', 'options': {'title': 'Error', 'message': '请先登录', 'timeout': 3}}
count = 0
disc_dbname = get_module_dbname('discount')
async with DBPools().sqlorContext('sage') as sor:
# Get all users (filtered by org if not owner)
if userorgid == '0':
users = await sor.sqlExe('SELECT id, orgid FROM users', {})
else:
users = await sor.sqlExe(
'SELECT id, orgid FROM users WHERE orgid = ${oid}$',
{'oid': userorgid}
)
if not users:
return {'widgettype': 'Message', 'options': {'title': '提示', 'message': '该机构下无用户', 'type': 'warning', 'timeout': 3}}
async with DBPools().sqlorContext(disc_dbname) as disc_sor:
for u in users:
existing = await disc_sor.sqlExe(
'SELECT id FROM discount_customer_bind WHERE customerid = ${cid}$',
{'cid': u.id}
)
if not existing:
await disc_sor.C('discount_customer_bind', {
'id': getID(),
'customerid': u.id,
'resellerid': userorgid,
'sale_id': None,
'promo_code_id': None,
'bind_type': '3',
})
count += 1
return {
'widgettype': 'Message',
'options': {
'title': '初始化完成',
'message': f'共 {len(users)} 个用户,新增 {count} 条自由客户记录',
'type': 'success',
'timeout': 0
}
}