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.

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