Skip to content
Draft
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Generated by Django 6.1.3 on 2026-11-19 10:58

import django.contrib.postgres.functions
from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("core", "0068_alter_procedure_last_updated_by"),
]

operations = [
migrations.AddField(
model_name="collectivite",
name="uuid",
field=models.UUIDField(
db_default=django.contrib.postgres.functions.RandomUUID(),
editable=False,
unique=True,
),
),
migrations.AddField(
model_name="communeprocedure",
name="commune_uuid",
field=models.UUIDField(blank=True, null=True),
),
migrations.AddField(
model_name="communeprocedure",
name="old_collectivite_type",
field=models.CharField(
choices=[
("COM", "Commune"),
("COMD", "Commune déléguée"),
("COMA", "Commune associée"),
("UNKWN", "Inconnu"),
],
default="COM",
verbose_name="Type de collectivité",
),
),
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Generated by Django 6.1.3 on 2026-11-19 10:59

import logging

from django.db import migrations

from docurba.core.models import CommuneProcedure

logger = logging.getLogger(__name__)


def fill_commune_procedure_commune_uuid(apps, schema_editor) -> None: # noqa: ANN001, ARG001
# Run the script once in wet run mode to check if it succeeds.
CommuneProcedure.update_commune_uuid()
CommuneProcedure.update_commune_uuid(save=True)


class Migration(migrations.Migration):
dependencies = [
("core", "0069_collectivite_uuid_communeprocedure_commune_uuid"),
]

operations = [
migrations.RunPython(
fill_commune_procedure_commune_uuid,
reverse_code=migrations.RunPython.noop,
elidable=True,
)
]
130 changes: 128 additions & 2 deletions django/docurba/core/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@
from datetime import datetime
from enum import IntEnum, StrEnum, auto
from functools import cached_property
from itertools import batched
from math import ceil
from operator import attrgetter
from typing import ClassVar, Self

from django.contrib.postgres.fields import ArrayField
from django.contrib.postgres.functions import RandomUUID, TransactionNow
from django.core.exceptions import PermissionDenied, ValidationError
from django.core.validators import MinValueValidator
from django.db import connection, models
from django.db import connection, models, transaction
from django.db.models import Value
from django.db.models.aggregates import StringAgg
from django.db.models.constraints import UniqueConstraint
Expand Down Expand Up @@ -411,7 +413,7 @@ class Procedure(models.Model):
db_constraint=False,
null=True,
to_field="code_insee_unique",
)
) # NOTE(cms): replace me by collectivite.uuid after this pull request.
created_at = models.DateTimeField(db_default=TransactionNow(), null=True)
last_updated_at = models.DateTimeField(db_default=TransactionNow(), null=True)
# Procedure updated "in cascade" when the parent procedure is.
Expand Down Expand Up @@ -1398,6 +1400,7 @@ def filter_by_code(self, code: str) -> Self:

class Collectivite(models.Model):
id = models.CharField(primary_key=True) # Au format code_type
uuid = models.UUIDField(db_default=RandomUUID(), editable=False, unique=True)
code_insee_unique = models.CharField( # noqa: DJ001
unique=True,
null=True,
Expand Down Expand Up @@ -1674,6 +1677,10 @@ def libelle_code_etat_complet(self) -> str:

class CommuneProcedure(models.Model): # noqa: DJ008
id = models.UUIDField(primary_key=True, db_default=RandomUUID())
commune_uuid = models.UUIDField(
blank=True,
null=True,
) # To be renamed `commune`.`

# Created for Nuxt before Django models were here.
# It should be refactored when working on the COG.
Expand Down Expand Up @@ -1705,6 +1712,11 @@ class CommuneProcedure(models.Model): # noqa: DJ008
choices=core_enums.CommuneType,
default=core_enums.CommuneType.COM,
)
old_collectivite_type = models.CharField(
verbose_name="Type de collectivité",
choices=core_enums.CommuneType,
default=core_enums.CommuneType.COM,
)
opposable = models.BooleanField(verbose_name="Est opposable", default=False)
# Denormalized version of commune.departement.code_insee already existing in production.
# Real type is TextField but I used a Charfiel here for performance reasons.
Expand Down Expand Up @@ -1751,6 +1763,120 @@ class Meta:
models.Index(name="test_idx", fields=["procedure_id", "collectivite_code"]),
]

@classmethod
def update_commune_uuid(cls, save: bool = False) -> None: # noqa: FBT001, FBT002, PLR0915
"""
Update CommuneProcedure.commune_uuid in bulk
and try to update outdated cls.collectivite_type at the same time.
""" # noqa: D205
cp_pks = cls.objects.filter(commune_uuid__isnull=True).values_list(
"pk", flat=True
)
can_be_updated_counter = 0
updated_counter = 0
not_existing_counter = 0

batches = ceil(len(cp_pks) / 2000)
for i, batch_pks in enumerate(batched(cp_pks, 2000, strict=False), 1):
to_be_created = []
to_be_updated = []
logger.info("Checking communes procedures (%d/%d).", i, batches)
qs = cls.objects.filter(
pk__in=batch_pks
).select_related(
"procedure"
) # can't use select related because it creates an inner join, not a left join.
for cp in qs:
can_be_updated_counter += 1
uuid = None
try:
uuid = cp.commune.uuid
updated_counter += 1
except Commune.DoesNotExist:
results = Commune.objects.filter(code_insee=cp.collectivite_code)
match results.count():
case 0:
# Commune does not exist. Stop here.
not_existing_counter += 1
logger.info(
"Commune not existing. %s",
cp.collectivite_code,
)
continue
case 1:
found_commune = results.first()
logger.info(
"A %s became a %s.; Procedure: %s; commune: %s;",
cp.collectivite_type,
found_commune.type,
cp.procedure.pk,
found_commune.code_insee,
)
if (
cp.collectivite_type != core_enums.CommuneType.COM
and found_commune.type == core_enums.CommuneType.COM
):
# We should delete the "old nouvelle commune" from the "perimetre"
# but Commune does not handle de-merging communes for the moment.
# There are very few cases so we could do it manually.
pass
elif (
cp.collectivite_type == core_enums.CommuneType.COM
and found_commune.type != core_enums.CommuneType.COM
):
nouvelle_code_insee = found_commune.nouvelle.code_insee
if (
nouvelle_code_insee
not in cp.procedure.perimetre_through.values_list(
"commune__code_insee", flat=True
)
):
# Add it
logger.info(
"Creating a CommuneProcedure: %s; commune: %s; nouvelle %s",
cp.procedure.pk,
found_commune.code_insee,
nouvelle_code_insee,
)
new_cp = cls(
collectivite_code=found_commune.nouvelle.code_insee,
collectivite_type=found_commune.nouvelle.type,
procedure_id=cp.procedure_id,
opposable=False,
commune_uuid=found_commune.nouvelle.uuid,
)
to_be_created.append(new_cp)

cp.old_collectivite_type = cp.collectivite_type
cp.collectivite_type = found_commune.type
uuid = found_commune.uuid
updated_counter += 1
case _:
logger.info(
"Multiple communes found. Skipping. %s",
cp.collectivite_code,
)
continue
cp.commune_uuid = uuid
to_be_updated.append(cp)
if save:
with transaction.atomic():
cls.objects.bulk_create(to_be_created)
cls.objects.bulk_update(
to_be_updated,
fields=[
"commune_uuid",
"collectivite_type",
"old_collectivite_type",
],
)

logger.info("Not existing: %s", not_existing_counter)
ignored_obj = cls.objects.filter(commune_uuid__isnull=True).count()
logger.info("CommuneProcedure without commune_uuid: %s", ignored_obj)
logger.info("Can be updated: %s", can_be_updated_counter)
logger.info("Successfully updated %s CommuneProcedure", updated_counter)


class MaterializedViewFlatMembershipQuerySet(models.QuerySet):
def create(self, *args: list, **kwargs: dict) -> Exception: # noqa: ARG002
Expand Down
7 changes: 3 additions & 4 deletions django/tests/core/factories.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,13 +101,12 @@ class Params:

class Meta:
model = core_models.Commune
django_get_or_create = ("code_insee_unique",)

id = factory.LazyAttribute(lambda o: f"{o.code_insee_unique}_{o.type}")
code_insee_unique = factory.LazyAttribute(lambda o: f"{o.code_insee}")
code_insee = factory.fuzzy.FuzzyChoice(COMMUNES.keys())
code_insee_unique = factory.SelfAttribute("code_insee")
type = core_enums.CommuneType.COM # Don't mess with COMD and COMA
nom = factory.LazyAttribute(lambda o: COMMUNES[o.code_insee_unique]["name"])
nom = factory.LazyAttribute(lambda o: COMMUNES[o.code_insee]["name"])
competence_plan = False
competence_schema = False

Expand Down Expand Up @@ -328,7 +327,7 @@ class Meta:
lambda o: f"{o.collectivite_code}_{o.collectivite_type}"
)
procedure = factory.SubFactory(ProcedureFactory)
collectivite_code = factory.SelfAttribute("commune.code_insee_unique")
collectivite_code = factory.SelfAttribute("commune.code_insee")
collectivite_type = factory.SelfAttribute("commune.type")
opposable = False
departement = factory.SelfAttribute("commune.departement.code_insee")
Expand Down
Loading