|
| 1 | +# Generated by Django 5.1.6 on 2025-04-15 07:15 |
| 2 | + |
| 3 | +from django.db import migrations, models |
| 4 | +from django.db.models import Count |
| 5 | + |
| 6 | +from qfdmo.models.acteur import ActeurStatus |
| 7 | + |
| 8 | + |
| 9 | +def suffix_external_id_for_digitals(apps, schema_editor): |
| 10 | + Acteur = apps.get_model("qfdmo", "Acteur") |
| 11 | + for acteur in Acteur.objects.filter(acteur_type__code="digital"): |
| 12 | + if ( |
| 13 | + not acteur.identifiant_externe.endswith("_d") |
| 14 | + and acteur.identifiant_unique.endswith("_d") |
| 15 | + and acteur.identifiant_externe in acteur.identifiant_unique |
| 16 | + ): |
| 17 | + acteur.identifiant_externe = f"{acteur.identifiant_externe}_d" |
| 18 | + acteur.save() |
| 19 | + |
| 20 | + |
| 21 | +def index_external_ids(apps, schema_editor): |
| 22 | + Acteur = apps.get_model("qfdmo", "Acteur") |
| 23 | + # Trouver tous les couples source_id/identifiant_externe en doublon |
| 24 | + acteur_with_same_couple = ( |
| 25 | + Acteur.objects.filter( |
| 26 | + source_id__isnull=False, identifiant_externe__isnull=False |
| 27 | + ) |
| 28 | + .values("source_id", "identifiant_externe") |
| 29 | + .annotate(count=Count("identifiant_unique")) |
| 30 | + .filter(count__gt=1) |
| 31 | + ) |
| 32 | + |
| 33 | + for couple in acteur_with_same_couple: |
| 34 | + acteurs = Acteur.objects.filter( |
| 35 | + source_id=couple["source_id"], |
| 36 | + identifiant_externe=couple["identifiant_externe"], |
| 37 | + ).order_by( |
| 38 | + "statut" |
| 39 | + ) # ACTIF first |
| 40 | + |
| 41 | + # Index external_id from the second one |
| 42 | + for i, acteur in enumerate(acteurs[1:], 2): |
| 43 | + nouveau_identifiant = f"{acteur.identifiant_externe}_{i-1}" |
| 44 | + acteur.identifiant_externe = nouveau_identifiant |
| 45 | + acteur.statut = ActeurStatus.INACTIF |
| 46 | + acteur.save() |
| 47 | + |
| 48 | + print( |
| 49 | + f"Indexé: {couple['source_id']=}, {couple['identifiant_externe']=}, " |
| 50 | + f"nouveau={nouveau_identifiant}, statut={acteur.statut}" |
| 51 | + ) |
| 52 | + |
| 53 | + |
| 54 | +class Migration(migrations.Migration): |
| 55 | + |
| 56 | + dependencies = [ |
| 57 | + ("qfdmo", "0150_acteur_siret_is_closed_and_more"), |
| 58 | + ] |
| 59 | + |
| 60 | + operations = [ |
| 61 | + migrations.RunPython( |
| 62 | + code=suffix_external_id_for_digitals, |
| 63 | + reverse_code=migrations.RunPython.noop, |
| 64 | + ), |
| 65 | + migrations.RunPython( |
| 66 | + code=index_external_ids, |
| 67 | + reverse_code=migrations.RunPython.noop, |
| 68 | + ), |
| 69 | + migrations.AddConstraint( |
| 70 | + model_name="acteur", |
| 71 | + constraint=models.UniqueConstraint( |
| 72 | + fields=("source_id", "identifiant_externe"), |
| 73 | + name="acteur_unique_by_source_and_external_id", |
| 74 | + ), |
| 75 | + ), |
| 76 | + ] |
0 commit comments