You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
1.8 KiB

  1. from django.conf import settings
  2. from django.contrib.auth.models import User
  3. from django.db.models.signals import m2m_changed, post_save, pre_delete
  4. from django.dispatch import receiver
  5. from .models import Project, Role, RoleMapping
  6. @receiver(post_save, sender=RoleMapping)
  7. def add_linked_project(sender, instance, created, **kwargs):
  8. if not created:
  9. return
  10. userInstance = instance.user
  11. projectInstance = instance.project
  12. if userInstance and projectInstance:
  13. user = User.objects.get(pk=userInstance.pk)
  14. project = Project.objects.get(pk=projectInstance.pk)
  15. user.projects.add(project)
  16. user.save()
  17. @receiver(m2m_changed, sender=Project.users.through)
  18. def remove_mapping_on_remove_user_from_project(sender, instance, action, reverse, **kwargs):
  19. # if reverse is True, pk_set is project_ids and instance is user.
  20. # else, pk_set is user_ids and instance is project.
  21. user_ids = kwargs['pk_set']
  22. if action.startswith('post_remove') and not reverse:
  23. RoleMapping.objects.filter(user__in=user_ids, project=instance).delete()
  24. elif action.startswith('post_add') and not reverse:
  25. admin_role = Role.objects.get(name=settings.ROLE_PROJECT_ADMIN)
  26. RoleMapping.objects.bulk_create(
  27. [RoleMapping(role=admin_role, project=instance, user_id=user)
  28. for user in user_ids
  29. if not RoleMapping.objects.filter(project=instance, user_id=user).exists()]
  30. )
  31. @receiver(pre_delete, sender=RoleMapping)
  32. def delete_linked_project(sender, instance, using, **kwargs):
  33. userInstance = instance.user
  34. projectInstance = instance.project
  35. if userInstance and projectInstance:
  36. user = User.objects.get(pk=userInstance.pk)
  37. project = Project.objects.get(pk=projectInstance.pk)
  38. user.projects.remove(project)
  39. user.save()