# Generated by Django 3.2.20 on 2023-09-14 09:50

from django.db import migrations


def set_journal_entry_period(apps, schema_editor):
    JournalEntry = apps.get_model("leprikon", "JournalEntry")
    SchoolYearPeriod = apps.get_model("leprikon", "SchoolYearPeriod")
    for entry in JournalEntry.objects.filter(
        journal__school_year_division__isnull=False, period__isnull=True
    ).select_related("journal"):
        entry.period = (
            SchoolYearPeriod.objects.filter(
                school_year_division_id=entry.journal.school_year_division_id,
            )
            .exclude(
                start__gt=entry.date,
                end__lt=entry.date,
            )
            .first()
            or SchoolYearPeriod.objects.filter(
                school_year_division_id=entry.journal.school_year_division_id,
            ).first()
        )
        entry.save()


class Migration(migrations.Migration):
    dependencies = [
        ("leprikon", "0081_min_due_date_days"),
    ]

    operations = [
        migrations.RunPython(set_journal_entry_period),
    ]
