From 733ab1ec32407e11bdaf238c8cce17d3ca9f430a Mon Sep 17 00:00:00 2001
From: Marte Fossum <marte.fossum@usit.uio.no>
Date: Wed, 25 Jan 2023 15:17:32 +0100
Subject: [PATCH] Hide deleted units from view

---
 greg/models.py                    |  7 +++++--
 greg/tasks.py                     |  2 +-
 greg/tests/models/test_sponsor.py | 15 +++++++++++++--
 3 files changed, 19 insertions(+), 5 deletions(-)

diff --git a/greg/models.py b/greg/models.py
index 189cae60..8b82a755 100644
--- a/greg/models.py
+++ b/greg/models.py
@@ -643,7 +643,7 @@ class Sponsor(BaseModel):
             models.UniqueConstraint(name="unique_feide_id", fields=["feide_id"])
         ]
 
-    def get_allowed_units(self) -> set[OrganizationalUnit]:
+    def get_allowed_units(self) -> list[OrganizationalUnit]:
         """
         Fetch every unit the sponsor has access to.
 
@@ -659,7 +659,10 @@ class Sponsor(BaseModel):
 
         # Add units accessible through direct access
         units = units.union({i.organizational_unit for i in connections})
-        return units
+
+        # Remove units that are deleted
+        units_filtered = [unit for unit in units if not unit.deleted]
+        return units_filtered
 
 
 class SponsorOrganizationalUnit(BaseModel):
diff --git a/greg/tasks.py b/greg/tasks.py
index ad6b3af9..f0464dc5 100644
--- a/greg/tasks.py
+++ b/greg/tasks.py
@@ -41,7 +41,7 @@ def notify_sponsors_roles_ending() -> list[str]:
 
     # Map sponsors with email to units
     sponsors = Sponsor.objects.filter(work_email__isnull=False)
-    sp2unit = {s.id: list(s.get_allowed_units()) for s in sponsors}
+    sp2unit = {s.id: s.get_allowed_units() for s in sponsors}
 
     # Map sponsors to ending roles
     # Make sure only the sponsor(s) closest to the role is notified
diff --git a/greg/tests/models/test_sponsor.py b/greg/tests/models/test_sponsor.py
index b9533072..dd82aecd 100644
--- a/greg/tests/models/test_sponsor.py
+++ b/greg/tests/models/test_sponsor.py
@@ -81,9 +81,20 @@ def test_get_allowed(sponsor_foo, unit1, unit2):
     unit2.save()
 
     # Without hier access only get unit connected to
-    assert sponsor_foo.get_allowed_units() == {unit1}
+    assert sponsor_foo.get_allowed_units() == [unit1]
 
     # With hier access also get units below
     spu.hierarchical_access = True
     spu.save()
-    assert sponsor_foo.get_allowed_units() == {unit1, unit2}
+    assert sponsor_foo.get_allowed_units() == [unit1, unit2]
+
+    # Don't get deleted units
+    unit2.deleted = True
+    unit2.save()
+    assert sponsor_foo.get_allowed_units() == [unit1]
+
+    unit2.deleted = False
+    unit1.deleted = True
+    unit2.save()
+    unit1.save()
+    assert sponsor_foo.get_allowed_units() == [unit2]
-- 
GitLab