Files
Django/merchant_ops/services/bootstrap.py

57 lines
2.0 KiB
Python

"""初始化权限码与商家默认角色。"""
from merchant_ops.constants import CLUB_ID_DEFAULT, PERMISSION_DEFINITIONS, SYSTEM_ROLE_TEMPLATES
from merchant_ops.models import (
MerchantStaffPermission, MerchantStaffRole, MerchantStaffRolePermission,
)
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 ensure_system_role_templates():
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,
},
)
for perm in tpl['permissions']:
MerchantStaffRolePermission.objects.get_or_create(
role=role, perm_code=perm,
)
def ensure_merchant_roles(merchant_id):
"""为商家复制系统角色模板(若尚未存在)。"""
ensure_system_role_templates()
templates = MerchantStaffRole.query.filter(merchant_id=None, status=1)
for tpl in templates:
role, created = 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,
},
)
if created:
for rp in tpl.role_permissions.all():
MerchantStaffRolePermission.objects.get_or_create(
role=role, perm_code=rp.perm_code,
)