Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tech: suppression de la méthode member_required #5268

Merged
merged 4 commits into from
Dec 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 1 addition & 13 deletions itou/common_apps/organizations/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from django.conf import settings
from django.db import models
from django.db.models import Exists, OuterRef, Prefetch, Q
from django.db.models import Prefetch, Q
from django.forms import ValidationError
from django.utils import timezone

Expand All @@ -15,18 +15,6 @@ class OrganizationQuerySet(models.QuerySet):
Common methods used by Company, PrescriberOrganization and Institution models query sets.
"""

def member_required(self, user):
membership_model = self.model.members.through
# through_fields contains a tuple like ("company", "user")
structure_field, _user_field = self.model.members.rel.through_fields
return self.filter(
Exists(
membership_model.objects.filter(
user=user, is_active=True, user__is_active=True, **{structure_field: OuterRef("pk")}
)
)
)

def prefetch_active_memberships(self):
membership_model = self.model.members.through
membership_set_related_name = membership_model.user.field.remote_field.get_accessor_name()
Expand Down
4 changes: 3 additions & 1 deletion itou/www/apply/views/process_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -563,7 +563,9 @@ class AcceptHTMXFragmentView(TemplateView):
def setup(self, request, company_pk=None, *args, **kwargs):
super().setup(request, *args, **kwargs)

company = get_object_or_404(Company.objects.member_required(request.user), pk=company_pk)
company = get_object_or_404(
Company.objects.filter(pk__in={org.pk for org in request.organizations}), pk=company_pk
)
self.form_accept = AcceptForm(company=company, data=request.POST or None)

def get_context_data(self, **kwargs):
Expand Down
12 changes: 8 additions & 4 deletions itou/www/apply/views/submit_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -816,7 +816,9 @@ def eligibility_for_hire(
job_seeker_public_id,
template_name="apply/submit/eligibility_for_hire.html",
):
company = get_object_or_404(Company.objects.member_required(request.user), pk=company_pk)
company = get_object_or_404(
Company.objects.filter(pk__in={org.pk for org in request.organizations}), pk=company_pk
)
job_seeker = get_object_or_404(User.objects.filter(kind=UserKind.JOB_SEEKER), public_id=job_seeker_public_id)
_check_job_seeker_approval(request, job_seeker, company)
next_url = reverse(
Expand Down Expand Up @@ -852,7 +854,7 @@ def geiq_eligibility_for_hire(
template_name="apply/submit/geiq_eligibility_for_hire.html",
):
company = get_object_or_404(
Company.objects.member_required(request.user).filter(kind=CompanyKind.GEIQ), pk=company_pk
Company.objects.filter(pk__in={org.pk for org in request.organizations}, kind=CompanyKind.GEIQ), pk=company_pk
)
job_seeker = get_object_or_404(User.objects.filter(kind=UserKind.JOB_SEEKER), public_id=job_seeker_public_id)
next_url = reverse(
Expand Down Expand Up @@ -884,7 +886,7 @@ def geiq_eligibility_for_hire(
@login_required
def geiq_eligibility_criteria_for_hire(request, company_pk, job_seeker_public_id):
company = get_object_or_404(
Company.objects.member_required(request.user).filter(kind=CompanyKind.GEIQ), pk=company_pk
Company.objects.filter(pk__in={org.pk for org in request.organizations}, kind=CompanyKind.GEIQ), pk=company_pk
)
job_seeker = get_object_or_404(User.objects.filter(kind=UserKind.JOB_SEEKER), public_id=job_seeker_public_id)
return common_views._geiq_eligibility_criteria(
Expand All @@ -901,7 +903,9 @@ def hire_confirmation(
job_seeker_public_id,
template_name="apply/submit/hire_confirmation.html",
):
company = get_object_or_404(Company.objects.member_required(request.user), pk=company_pk)
company = get_object_or_404(
Company.objects.filter(pk__in={org.pk for org in request.organizations}), pk=company_pk
)
job_seeker = get_object_or_404(
User.objects.filter(kind=UserKind.JOB_SEEKER).select_related("jobseeker_profile"),
public_id=job_seeker_public_id,
Expand Down
31 changes: 14 additions & 17 deletions itou/www/dashboard/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import PermissionDenied
from django.db.models import F
from django.http import Http404, HttpResponseForbidden, HttpResponseRedirect
from django.http import Http404, HttpResponseBadRequest, HttpResponseForbidden, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse, reverse_lazy
from django.utils import timezone
Expand All @@ -19,15 +19,12 @@
from itou.approvals.enums import ProlongationRequestStatus
from itou.approvals.models import ProlongationRequest
from itou.companies.enums import CompanyKind
from itou.companies.models import Company
from itou.employee_record.enums import Status
from itou.employee_record.models import EmployeeRecord
from itou.geiq.models import ImplementationAssessmentCampaign
from itou.institutions.enums import InstitutionKind
from itou.institutions.models import Institution
from itou.job_applications.enums import JobApplicationState
from itou.openid_connect.inclusion_connect import constants as ic_constants
from itou.prescribers.models import PrescriberOrganization
from itou.siae_evaluations.models import EvaluatedSiae, EvaluationCampaign
from itou.users.enums import MATOMO_ACCOUNT_TYPE, IdentityProvider, UserKind
from itou.users.models import User
Expand Down Expand Up @@ -321,19 +318,19 @@ def edit_job_seeker_info(request, job_seeker_public_id, template_name="dashboard
@login_required
@require_POST
def switch_organization(request):
pk = request.POST["organization_id"]
match request.user.kind:
case UserKind.EMPLOYER:
queryset = Company.objects.active_or_in_grace_period().member_required(request.user)
case UserKind.PRESCRIBER:
queryset = PrescriberOrganization.objects.member_required(request.user)
case UserKind.LABOR_INSPECTOR:
queryset = Institution.objects.member_required(request.user)
case _:
raise Http404()

organization = get_object_or_404(queryset, pk=pk)
request.session[global_constants.ITOU_SESSION_CURRENT_ORGANIZATION_KEY] = organization.pk
try:
pk = int(request.POST["organization_id"])
except (KeyError, ValueError):
return HttpResponseBadRequest(b"organization_id key is missing")
xavfernandez marked this conversation as resolved.
Show resolved Hide resolved

if request.user.kind not in {
UserKind.EMPLOYER,
UserKind.PRESCRIBER,
UserKind.LABOR_INSPECTOR,
} or pk not in {organization.pk for organization in request.organizations}:
raise Http404()

request.session[global_constants.ITOU_SESSION_CURRENT_ORGANIZATION_KEY] = pk
return HttpResponseRedirect(reverse("dashboard:index"))


Expand Down
14 changes: 0 additions & 14 deletions tests/companies/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,20 +271,6 @@ def test_add_or_activate_member(self):


class TestCompanyQuerySet:
def test_member_required(self):
company = CompanyFactory()
user = EmployerFactory()
assert Company.objects.member_required(user).count() == 0

company.add_or_activate_member(user)
assert Company.objects.member_required(user).get() == company

membership = company.memberships.get()
membership.is_active = False
membership.save(update_fields=("is_active",))

assert Company.objects.member_required(user).count() == 0

def test_with_count_recent_received_job_applications(self):
company = CompanyFactory()
model = JobApplicationFactory._meta.model
Expand Down
16 changes: 0 additions & 16 deletions tests/institutions/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,22 +71,6 @@ def test_add_or_activate_member(self):
institution.add_or_activate_member(wrong_kind_user)


class TestInstitutionQuerySet:
def test_member_required(self):
institution = InstitutionFactory()
user = LaborInspectorFactory()
assert Institution.objects.member_required(user).count() == 0

institution.add_or_activate_member(user)
assert Institution.objects.member_required(user).get() == institution

membership = institution.memberships.get()
membership.is_active = False
membership.save(update_fields=("is_active",))

assert Institution.objects.member_required(user).count() == 0


def test_deactivate_last_admin(admin_client, mailoutbox):
institution = InstitutionWithMembershipFactory(department="")
membership = institution.memberships.first()
Expand Down
16 changes: 0 additions & 16 deletions tests/prescribers/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,22 +246,6 @@ def test_update_prescriber_with_api_entreprise(self, settings):
assert organization.is_head_office is True


class TestPrescriberOrganizationQuerySet:
def test_member_required(self):
organization = PrescriberOrganizationFactory()
user = PrescriberFactory()
assert PrescriberOrganization.objects.member_required(user).count() == 0

organization.add_or_activate_member(user)
assert PrescriberOrganization.objects.member_required(user).get() == organization

membership = organization.memberships.get()
membership.is_active = False
membership.save(update_fields=("is_active",))

assert PrescriberOrganization.objects.member_required(user).count() == 0


class TestPrescriberOrganizationAdmin:
ACCEPT_BUTTON_LABEL = "Valider l'habilitation"
REFUSE_BUTTON_LABEL = "Refuser l'habilitation"
Expand Down
10 changes: 1 addition & 9 deletions tests/www/apply/__snapshots__/test_submit.ambr
Original file line number Diff line number Diff line change
Expand Up @@ -211,15 +211,7 @@
"companies_company"."rdv_solidarites_id"
FROM "companies_company"
WHERE (NOT ("companies_company"."siret" = %s)
AND EXISTS
(SELECT %s AS "a"
FROM "companies_companymembership" U0
INNER JOIN "users_user" U2 ON (U0."user_id" = U2."id")
WHERE (U0."company_id" = ("companies_company"."id")
AND U0."is_active"
AND U0."user_id" = %s
AND U2."is_active")
LIMIT 1)
AND "companies_company"."id" IN (%s)
AND "companies_company"."id" = %s)
LIMIT 21
''',
Expand Down
44 changes: 44 additions & 0 deletions tests/www/dashboard/test_switch_organization.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,22 @@ def test_cannot_switch_to_inactive_company_after_grace_period(self, client):
assert response.status_code == 200
assert response.context["request"].current_organization == company

def test_bad_request(self, client):
url = reverse("dashboard:switch_organization")

company = CompanyFactory(with_membership=True)
user = company.members.first()
client.force_login(user)

related_company = CompanyFactory(with_membership=True)
related_company.members.add(user)

response = client.post(url)
assert response.status_code == 400

response = client.post(url, data={"organization_id": "Une entreprise entière"})
assert response.status_code == 400


class TestSwitchOrganization:
def test_not_allowed_user(self, client):
Expand Down Expand Up @@ -142,6 +158,20 @@ def test_usual_case(self, client):
assert response.status_code == 200
assert response.context["request"].current_organization == orga2

def test_bad_request(self, client):
url = reverse("dashboard:switch_organization")

user = PrescriberFactory()
prescribers_factories.PrescriberMembershipFactory(user=user)
prescribers_factories.PrescriberMembershipFactory(user=user)
client.force_login(user)

response = client.post(url)
assert response.status_code == 400

response = client.post(url, data={"organization_id": "Une orga entière"})
assert response.status_code == 400


class TestSwitchInstitution:
def test_not_allowed_user(self, client):
Expand Down Expand Up @@ -179,3 +209,17 @@ def test_usual_case(self, client):
response = client.get(reverse("dashboard:index"))
assert response.status_code == 200
assert response.context["request"].current_organization == institution2

def test_bad_request(self, client):
url = reverse("dashboard:switch_organization")

user = LaborInspectorFactory()
InstitutionMembershipFactory(user=user).institution
InstitutionMembershipFactory(user=user).institution
client.force_login(user)

response = client.post(url)
assert response.status_code == 400

response = client.post(url, data={"organization_id": "Une institution entière"})
assert response.status_code == 400
Loading