Skip to content

Commit

Permalink
Accepter une demande d'habilitation et créer l'organisation correspon…
Browse files Browse the repository at this point in the history
…dante #593
  • Loading branch information
tut-tuuut authored Apr 7, 2022
2 parents 36f4d8f + cdb22d2 commit 6f2eb41
Show file tree
Hide file tree
Showing 5 changed files with 250 additions and 6 deletions.
35 changes: 32 additions & 3 deletions aidants_connect_habilitation/admin.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from django.conf import settings
from django.contrib import messages
from django.contrib.admin import ModelAdmin, StackedInline, TabularInline

from django_reverse_admin import ReverseModelAdmin
Expand All @@ -15,6 +16,7 @@
OrganisationRequest,
RequestMessage,
)
from aidants_connect_web.models import Organisation


class OrganisationRequestInline(VisibleToAdminMetier, TabularInline):
Expand Down Expand Up @@ -50,16 +52,43 @@ class MessageInline(VisibleToAdminMetier, StackedInline):

class OrganisationRequestAdmin(VisibleToAdminMetier, ReverseModelAdmin):
list_filter = ("status", RegionFilter, DepartmentFilter)
list_display = ("name", "issuer", "status")
raw_id_fields = ("issuer",)
readonly_fields = ("public_service_delegation_attestation", "uuid")
list_display = ("name", "issuer", "status", "data_pass_id")
search_fields = ("data_pass_id", "name")
raw_id_fields = ("issuer", "organisation")
readonly_fields = ("public_service_delegation_attestation", "uuid", "organisation")
inlines = (
AidantRequestInline,
MessageInline,
)
inline_type = "stacked"
inline_reverse = ("manager",)

actions = ("accept_request",)

def accept_request(self, request, queryset):
orgs_created = 0
for organisation_request in queryset:
try:
if organisation_request.accept_request_and_create_organisation():
orgs_created += 1
except Organisation.AlreadyExists as e:
self.message_user(request, e, level=messages.ERROR)
if orgs_created > 1:
self.message_user(
request,
f"{orgs_created} organisations ont été créées.",
level=messages.SUCCESS,
)
elif orgs_created == 1:
self.message_user(
request, "Une organisation a été créée.", level=messages.SUCCESS
)

accept_request.short_description = (
"Accepter les demandes sélectionnées "
"(créer les organisations et les aidants à former)"
)


if settings.AC_HABILITATION_FORM_ENABLED:
admin_site.register(Issuer, IssuerAdmin)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Generated by Django 3.2.12 on 2022-04-07 08:34

import django.db.models.deletion
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('aidants_connect_web', '0085_auto_20220329_0005'),
('aidants_connect_habilitation', '0017_auto_20220405_1655'),
]

operations = [
migrations.AddField(
model_name='organisationrequest',
name='organisation',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='aidants_connect_web.organisation'),
),
]
81 changes: 79 additions & 2 deletions aidants_connect_habilitation/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
from uuid import uuid4

from django.conf import settings
from django.db import models
from django.db import models, transaction
from django.db.models import SET_NULL, Q
from django.db.utils import IntegrityError
from django.dispatch import Signal
from django.http import HttpRequest
from django.urls import reverse
Expand All @@ -18,7 +19,12 @@
RequestOriginConstants,
RequestStatusConstants,
)
from aidants_connect_web.models import OrganisationType
from aidants_connect_web.models import (
Aidant,
HabilitationRequest,
Organisation,
OrganisationType,
)
from aidants_connect_web.utilities import generate_new_datapass_id

__all__ = [
Expand Down Expand Up @@ -162,6 +168,13 @@ class Meta:


class OrganisationRequest(models.Model):
organisation = models.ForeignKey(
Organisation,
null=True,
blank=True,
on_delete=models.SET_NULL,
)

issuer = models.ForeignKey(
Issuer,
on_delete=models.CASCADE,
Expand Down Expand Up @@ -281,6 +294,70 @@ def prepare_request_for_ac_validation(self, form_data: dict):
self.data_pass_id = int(f"{self.zipcode[:3]}{generate_new_datapass_id()}")
self.save()

@transaction.atomic
def accept_request_and_create_organisation(self):
if self.status != RequestStatusConstants.AC_VALIDATION_PROCESSING.name:
return False

try:
organisation = Organisation.objects.create(
name=self.name,
type=(self.type_other if self.type_other else self.type),
siret=self.siret,
address=self.address,
zipcode=self.zipcode,
city=self.city,
data_pass_id=self.data_pass_id,
)
except IntegrityError:
raise Organisation.AlreadyExists(
"Il existe déjà une organisation portant le n° datapass "
f"{self.data_pass_id}."
)

self.organisation = organisation
self.status = RequestStatusConstants.VALIDATED.name
self.save()

responsable_query = Aidant.objects.filter(username=self.manager.email)

if not responsable_query.exists():
responsable = Aidant.objects.create(
first_name=self.manager.first_name,
last_name=self.manager.last_name,
email=self.manager.email,
phone=self.manager.phone,
profession=self.manager.profession,
organisation=organisation,
can_create_mandats=False,
)

responsable.responsable_de.add(organisation)
responsable.save()
else:
responsable = responsable_query[0]
responsable.responsable_de.add(organisation)
responsable.save()

for aidant in self.aidant_requests.all():
HabilitationRequest.objects.create(
first_name=aidant.first_name,
last_name=aidant.last_name,
email=aidant.email,
profession=aidant.profession,
organisation=organisation,
)
if self.manager.is_aidant:
HabilitationRequest.objects.create(
first_name=self.manager.first_name,
last_name=self.manager.last_name,
email=self.manager.email,
profession=self.manager.profession,
organisation=organisation,
)

return True

class Meta:
constraints = [
models.CheckConstraint(
Expand Down
117 changes: 116 additions & 1 deletion aidants_connect_habilitation/tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,18 @@

from freezegun import freeze_time

from aidants_connect.common.constants import RequestOriginConstants
from aidants_connect.common.constants import (
RequestOriginConstants,
RequestStatusConstants,
)
from aidants_connect_habilitation.models import Issuer, IssuerEmailConfirmation
from aidants_connect_habilitation.tests.factories import (
AidantRequestFactory,
IssuerFactory,
OrganisationRequestFactory,
)
from aidants_connect_web.models import Aidant, HabilitationRequest, Organisation
from aidants_connect_web.tests.factories import AidantFactory, OrganisationFactory


@tag("models")
Expand Down Expand Up @@ -54,6 +60,115 @@ def test_manager_set_constraint(self):
OrganisationRequestFactory(manager=None)
self.assertIn("manager_set", str(cm.exception))

def prepare_data_for_nominal_case(self):
organisation_request = OrganisationRequestFactory(
status=RequestStatusConstants.AC_VALIDATION_PROCESSING.name,
data_pass_id=67255555,
)
organisation_request.manager.is_aidant = True
organisation_request.manager.save()
for _ in range(3):
AidantRequestFactory(organisation=organisation_request)
organisation_request.save()
return organisation_request

def prepare_data_with_existing_responsable(self):
organisation_request = OrganisationRequestFactory(
status=RequestStatusConstants.AC_VALIDATION_PROCESSING.name,
data_pass_id=69366666,
)
organisation_request.manager.is_aidant = True
organisation_request.manager.save()
# existing manager
AidantFactory(
email=organisation_request.manager.email,
username=organisation_request.manager.email,
can_create_mandats=False,
)
for _ in range(3):
AidantRequestFactory(organisation=organisation_request)
organisation_request.save()
return organisation_request

def test_accept_when_it_should_work_fine(self):
for organisation_request in (
self.prepare_data_for_nominal_case(),
self.prepare_data_with_existing_responsable(),
):
result = organisation_request.accept_request_and_create_organisation()

# verify if organisation was created
self.assertTrue(result, "Result of method call should be True")
self.assertTrue(
Organisation.objects.filter(
data_pass_id=organisation_request.data_pass_id
).exists(),
"Organisation should have been created",
)
organisation = Organisation.objects.get(
data_pass_id=organisation_request.data_pass_id
)

# verify if organisation was added to organisation_request
self.assertEqual(organisation_request.organisation, organisation)

# verify if responsable aidant account was properly created and added to org
self.assertEqual(
1,
Aidant.objects.filter(email=organisation_request.manager.email).count(),
)
responsable = Aidant.objects.get(email=organisation_request.manager.email)

# verify if responsable was added to organisation
self.assertIn(responsable, organisation.responsables.all())
self.assertFalse(responsable.can_create_mandats)

# verify status
self.assertEqual(
organisation_request.status, RequestStatusConstants.VALIDATED.name
)

# verify if aidants were created
for aidant_request in organisation_request.aidant_requests.all():
self.assertTrue(
HabilitationRequest.objects.filter(
organisation=organisation, email=aidant_request.email
).exists(),
f"Habilitation request was not created for {aidant_request.email}",
)
# check if responsable is on the list of aidants too
self.assertTrue(
HabilitationRequest.objects.filter(
organisation=organisation, email=organisation_request.manager.email
).exists()
)

def test_accept_fails_when_organisation_already_exists(self):
def prepare_data():
OrganisationFactory(
data_pass_id=67245456,
)
organisation_request = OrganisationRequestFactory(
status=RequestStatusConstants.AC_VALIDATION_PROCESSING.name,
data_pass_id=67245456,
)
organisation_request.manager.is_aidant = True
organisation_request.manager.save()
for _ in range(3):
AidantRequestFactory(organisation=organisation_request)
organisation_request.save()
return organisation_request

organisation_request = prepare_data()
with self.assertRaises(Organisation.AlreadyExists):
organisation_request.accept_request_and_create_organisation(),

# verify status
self.assertEqual(
organisation_request.status,
RequestStatusConstants.AC_VALIDATION_PROCESSING.name,
)


class TestIssuerEmailConfirmation(TestCase):
NOW = now()
Expand Down
3 changes: 3 additions & 0 deletions aidants_connect_web/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,9 @@ class Organisation(models.Model):
def __str__(self):
return f"{self.name}"

class AlreadyExists(Exception):
pass

@cached_property
def num_active_aidants(self):
return self.aidants.active().count()
Expand Down

0 comments on commit 6f2eb41

Please sign in to comment.