"""Create an admin user for the selected sub_distributor. Show the initial password.""" sub_distributor_id = params_kw.get('sub_distributor_id') or params_kw.get('id') if not sub_distributor_id: return {'widgettype': 'Error', 'options': {'title': 'Error', 'message': 'Missing sub_distributor_id', 'timeout': 3}} userorgid = await get_userorgid() if not userorgid: return {'widgettype': 'Error', 'options': {'title': 'Auth Error', 'message': 'Please login', 'timeout': 3}} dbname = get_module_dbname('supplychain') async with DBPools().sqlorContext(dbname) as sor: recs = await sor.sqlExe( 'SELECT id, sub_dist_name FROM sub_distributors WHERE id = ${sid}$', {'sid': sub_distributor_id} ) if not recs: return {'widgettype': 'Error', 'options': {'title': 'Error', 'message': '二级分销商不存在', 'timeout': 3}} sd = recs[0] org_id = sd.id admin_username = f'admin_{sub_distributor_id[:8]}' async with DBPools().sqlorContext('sage') as sor_sage: # Check/ensure org exists org_recs = await sor_sage.sqlExe( 'SELECT id FROM organization WHERE id = ${oid}$', {'oid': org_id} ) if not org_recs: await sor_sage.C('organization', { 'id': org_id, 'orgname': sd.sub_dist_name, }) # Check if admin already exists user_recs = await sor_sage.sqlExe( 'SELECT id FROM users WHERE username = ${un}$', {'un': admin_username} ) if user_recs: return { 'widgettype': 'Message', 'options': { 'title': '管理员已存在', 'message': f'管理员 {admin_username} 已存在,请用重置密码功能', 'type': 'warning', 'timeout': 5 } } # Generate password from uuid pwd = getID().replace('-','')[:12] user_id = getID() await sor_sage.C('users', { 'id': user_id, 'username': admin_username, 'password': password_encode(pwd), 'orgid': org_id, 'nick_name': sd.sub_dist_name + '管理员', 'user_status': '1', }) # Assign roles: logined + reseller.admin + reseller.operator for role_name in ['logined', 'reseller.admin', 'reseller.operator']: role_recs = await sor_sage.R('role', {'role': role_name}) if role_recs: await sor_sage.C('userrole', { 'id': getID(), 'userid': user_id, 'roleid': role_recs[0].id, }) return { 'widgettype': 'Message', 'options': { 'title': '管理员创建成功', 'message': f'用户名: {admin_username}\n初始密码: {pwd}\n请妥善保管,登录后建议修改', 'type': 'success', 'timeout': 0 } }