from __future__ import annotations from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import Group from .models import UserProfile ROLE_GROUP_MAP = { UserProfile.ROLE_OWNER: "owner", UserProfile.ROLE_MANAGER: "manager", UserProfile.ROLE_DRIVER: "driver", UserProfile.ROLE_CUSTOMER: "customer", UserProfile.ROLE_AUDITOR: "auditor", } MANAGED_GROUPS = set(ROLE_GROUP_MAP.values()) @receiver(post_save, sender=UserProfile) def sync_profile_role_to_groups(sender, instance: UserProfile, created: bool, **kwargs): """Keep Django Group membership in sync with the profile role. - Removes the user from managed role groups (owner/manager/driver/customer/auditor) - Adds the user to the group mapped from the current role - Lazily creates the Group if missing """ user = instance.user if user is None or not getattr(user, "pk", None): return # Remove from managed groups first (do not touch other unrelated groups) current_managed = user.groups.filter(name__in=MANAGED_GROUPS) if current_managed.exists(): user.groups.remove(*current_managed) # Add target group for role group_name = ROLE_GROUP_MAP.get(instance.role) if not group_name: return group, _ = Group.objects.get_or_create(name=group_name) user.groups.add(group)