"""为后台客服账号初始化 admin_assignment(数据范围,非功能权限)。""" import logging from django.core.management.base import BaseCommand from django.db import transaction from jituan.constants import CLUB_ID_DEFAULT, DATA_SCOPE_SINGLE, ADMIN_ROLE_LABELS from jituan.models import AdminAssignment from users.business_models import User logger = logging.getLogger(__name__) class Command(BaseCommand): help = '为 kefu 账号创建默认子公司任职(club=xq, CLUB_ADMIN);超管可不建 assignment' def add_arguments(self, parser): parser.add_argument( '--club-id', default=CLUB_ID_DEFAULT, help='目标俱乐部 ID,默认 xq', ) parser.add_argument( '--role-code', default='CLUB_ADMIN', help='任职角色码', ) parser.add_argument( '--dry-run', action='store_true', help='只打印不写入', ) def handle(self, *args, **options): club_id = options['club_id'] role_code = options['role_code'] dry_run = options['dry_run'] kefu_users = User.query.filter(UserType='kefu') created = 0 skipped = 0 with transaction.atomic(): for u in kefu_users: if u.IsSuperuser: skipped += 1 continue exists = AdminAssignment.query.filter( yonghuid=u.UserUID, club_id=club_id, role_code=role_code, ).exists() if exists: skipped += 1 continue if dry_run: self.stdout.write(f'would assign {u.UserUID} -> {club_id} {role_code}') created += 1 continue AdminAssignment.query.create( yonghuid=u.UserUID, club_id=club_id, role_code=role_code, data_scope=DATA_SCOPE_SINGLE, is_primary=True, status=1, ) created += 1 label = ADMIN_ROLE_LABELS.get(role_code, role_code) self.stdout.write(self.style.SUCCESS( f'完成:新建 {created} 条,跳过 {skipped} 条(club={club_id}, role={label})' ))