# Generated by Django 3.0.4 on 2020-03-25 14:40

from django.db import migrations, models
from django.db.models import Count, OuterRef, Q, Subquery
from django.utils.timezone import now


def fill_cancellation_date(apps, schema_editor):
    Order = apps.get_model('pretixbase', 'Order')
    LogEntry = apps.get_model('pretixbase', 'LogEntry')
    OrderPosition = apps.get_model('pretixbase', 'OrderPosition')

    s = OrderPosition.all.filter(
        order=OuterRef('pk'),
        canceled=False,
    ).order_by().values('order').annotate(k=Count('id')).values('k')
    for o in Order.objects.annotate(
            pcnt=Subquery(s)
    ).filter(
        Q(pcnt=0) | Q(pcnt__isnull=True) | Q(status="c")
    ).values('id').iterator():
        le = LogEntry.objects.filter(
            content_type__model="order",
            object_id=o['id'],
            action_type='pretix.event.order.canceled'
        ).order_by('-datetime').only('datetime').first()
        if le:
            Order.objects.filter(pk=o['id']).update(
                cancellation_date=le.datetime,
                last_modified=now()
            )


class Migration(migrations.Migration):
    dependencies = [
        ('pretixbase', '0148_cancellationrequest'),
    ]

    operations = [
        migrations.AddField(
            model_name='order',
            name='cancellation_date',
            field=models.DateTimeField(blank=True, null=True),
        ),
        migrations.RunPython(fill_cancellation_date, migrations.RunPython.noop)
    ]
