Files
Django/merchant_ops/services/bootstrap.py

97 lines
3.4 KiB
Python

"""初始化权限码与商家默认角色。"""
from merchant_ops.constants import CLUB_ID_DEFAULT, PERMISSION_DEFINITIONS, SYSTEM_ROLE_TEMPLATES
from merchant_ops.models import (
MerchantStaffPermission, MerchantStaffRole, MerchantStaffRolePermission,
)
_SYSTEM_ROLE_CODES = {t['role_code'] for t in SYSTEM_ROLE_TEMPLATES}
_SYSTEM_BOOTSTRAPPED = False
_MERCHANT_BOOTSTRAPPED = set()
def seed_global_permissions():
for idx, (code, name) in enumerate(PERMISSION_DEFINITIONS):
MerchantStaffPermission.objects.get_or_create(
perm_code=code,
defaults={'perm_name': name, 'sort_order': idx, 'status': 1},
)
def _sync_role_permissions(role, perm_codes):
"""同步角色权限(系统预置角色与模板保持一致)。"""
perm_codes = set(perm_codes or [])
existing = set(role.role_permissions.values_list('perm_code', flat=True))
for code in perm_codes - existing:
MerchantStaffRolePermission.objects.get_or_create(role=role, perm_code=code)
if role.is_system:
role.role_permissions.exclude(perm_code__in=perm_codes).delete()
def _system_roles_ready():
if not _SYSTEM_ROLE_CODES:
return False
existing = set(
MerchantStaffRole.query.filter(
merchant_id=None, is_system=True, status=1,
).values_list('role_code', flat=True)
)
if not _SYSTEM_ROLE_CODES <= existing:
return False
return MerchantStaffPermission.query.count() >= len(PERMISSION_DEFINITIONS)
def ensure_system_role_templates():
global _SYSTEM_BOOTSTRAPPED
if _SYSTEM_BOOTSTRAPPED or _system_roles_ready():
_SYSTEM_BOOTSTRAPPED = True
return
seed_global_permissions()
for tpl in SYSTEM_ROLE_TEMPLATES:
role, _ = MerchantStaffRole.objects.get_or_create(
merchant_id=None,
role_code=tpl['role_code'],
defaults={
'club_id': CLUB_ID_DEFAULT,
'role_name': tpl['role_name'],
'is_system': True,
'sort_order': tpl['sort_order'],
'status': 1,
},
)
_sync_role_permissions(role, tpl['permissions'])
_SYSTEM_BOOTSTRAPPED = True
def ensure_merchant_roles(merchant_id):
"""为商家复制系统角色模板。已初始化则直接返回,避免热路径全量同步拖垮 worker。"""
mid = str(merchant_id)
if mid in _MERCHANT_BOOTSTRAPPED:
return
existing_codes = set(
MerchantStaffRole.query.filter(
merchant_id=merchant_id, is_system=True, status=1,
).values_list('role_code', flat=True)
)
if _SYSTEM_ROLE_CODES and _SYSTEM_ROLE_CODES <= existing_codes:
_MERCHANT_BOOTSTRAPPED.add(mid)
return
ensure_system_role_templates()
templates = MerchantStaffRole.query.filter(merchant_id=None, status=1)
for tpl in templates:
role, _ = MerchantStaffRole.objects.get_or_create(
merchant_id=merchant_id,
role_code=tpl.role_code,
defaults={
'club_id': CLUB_ID_DEFAULT,
'role_name': tpl.role_name,
'is_system': True,
'sort_order': tpl.sort_order,
'status': 1,
},
)
tpl_perms = list(tpl.role_permissions.values_list('perm_code', flat=True))
_sync_role_permissions(role, tpl_perms)
_MERCHANT_BOOTSTRAPPED.add(mid)