# Generated by Django 5.0.14 on 2025-07-18 06:37

import django.db.models.deletion
import django.db.models.expressions
import django_fsm
from decimal import Decimal
from django.db import migrations, models
from tqdm import tqdm
def migrate_order(apps, schema_editor):
    Order = apps.get_model("wbportfolio", "Order")
    Trade = apps.get_model("wbportfolio", "Trade")
    objs = []
    qs = Trade.objects.filter(order_proposal__isnull=False).select_related("order_proposal")
    for order in tqdm(qs, total=qs.count()):
        objs.append(Order(
            order=order.order,
            value_date=order.order_proposal.trade_date,
            currency_fx_rate=order.currency_fx_rate,
            price=order.price,
            price_gross=order.price_gross,
            fees=order.fees,
            comment=order.comment,
            created=order.created,
            updated=order.updated,
            order_type=order.transaction_subtype,
            status=order.status,
            shares=order.shares,
            weighting=order.weighting,
            drift_factor=order.drift_factor,
            import_source=order.import_source,
            portfolio=order.portfolio,
            underlying_instrument=order.underlying_instrument,
            order_proposal=order.order_proposal,
        ))
    Order.objects.bulk_create(objs)
    qs.delete()

class Migration(migrations.Migration):

    dependencies = [
        ('io', '0008_importsource_resource_kwargs'),
        ('wbfdm', '0031_exchange_apply_round_lot_size_and_more'),
        ('wbportfolio', '0082_remove_tradeproposal_creator_and_more'),
    ]

    operations = [
        migrations.CreateModel(
            name='Order',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('order', models.PositiveIntegerField(db_index=True, editable=False, verbose_name='order')),
                ('value_date', models.DateField(help_text='The date that this transaction was valuated/paid.', verbose_name='Value Date')),
                ('currency_fx_rate', models.DecimalField(decimal_places=8, default=Decimal('1'), max_digits=14, verbose_name='FOREX rate')),
                ('price', models.DecimalField(decimal_places=4, help_text='The price per share.', max_digits=16, verbose_name='Price')),
                ('price_gross', models.DecimalField(decimal_places=4, help_text='The gross price per share.', max_digits=16, verbose_name='Gross Price')),
                ('fees', models.GeneratedField(db_persist=True, expression=django.db.models.expressions.CombinedExpression(models.F('price_gross'), '-', models.F('price')), output_field=models.DecimalField(decimal_places=4, max_digits=20))),
                ('total_value_gross', models.GeneratedField(db_persist=True, expression=django.db.models.expressions.CombinedExpression(models.F('price_gross'), '*', models.F('shares')), output_field=models.DecimalField(decimal_places=4, max_digits=20))),
                ('total_value', models.GeneratedField(db_persist=True, expression=django.db.models.expressions.CombinedExpression(models.F('price'), '*', models.F('shares')), output_field=models.DecimalField(decimal_places=4, max_digits=20))),
                ('total_value_fx_portfolio', models.GeneratedField(db_persist=True, expression=django.db.models.expressions.CombinedExpression(django.db.models.expressions.CombinedExpression(models.F('currency_fx_rate'), '*', models.F('price')), '*', models.F('shares')), output_field=models.DecimalField(decimal_places=4, max_digits=20))),
                ('total_value_gross_fx_portfolio', models.GeneratedField(db_persist=True, expression=django.db.models.expressions.CombinedExpression(django.db.models.expressions.CombinedExpression(models.F('currency_fx_rate'), '*', models.F('price_gross')), '*', models.F('shares')), output_field=models.DecimalField(decimal_places=4, max_digits=20))),
                ('comment', models.TextField(blank=True, default='', verbose_name='Comment')),
                ('created', models.DateTimeField(auto_now_add=True)),
                ('updated', models.DateTimeField(auto_now=True)),
                ('order_type', models.CharField(choices=[('REBALANCE', 'Rebalance'), ('DECREASE', 'Decrease'), ('INCREASE', 'Increase'), ('BUY', 'Buy'), ('SELL', 'Sell'), ('NO_CHANGE', 'No Change')], default='BUY', max_length=32, verbose_name='Trade Type')),
                ('status', django_fsm.FSMField(choices=[('DRAFT', 'Draft'), ('SUBMIT', 'Submit'), ('EXECUTED', 'Executed'), ('CONFIRMED', 'Confirmed'), ('FAILED', 'Failed')], default='CONFIRMED', max_length=50, verbose_name='Status')),
                ('shares', models.DecimalField(decimal_places=4, default=Decimal('0.0'), help_text='The number of shares that were traded.', max_digits=15, verbose_name='Shares')),
                ('weighting', models.DecimalField(decimal_places=8, default=Decimal('0'), help_text='The weight to be multiplied against the target', max_digits=9, verbose_name='Weight')),
                ('drift_factor', models.DecimalField(decimal_places=16, default=Decimal('1'), help_text='Drift factor to be applied to the previous portfolio weight to get the actual effective weight including daily return', max_digits=19, verbose_name='Drift Factor')),
            ],
            options={
                'verbose_name': 'Order',
                'verbose_name_plural': 'Orders',
                'ordering': ('order',),
                'abstract': False,
            },
        ),
        migrations.AddField(
            model_name='order',
            name='order_proposal',
            field=models.ForeignKey(help_text='The Order Proposal this trade is coming from',
                                    on_delete=django.db.models.deletion.CASCADE, related_name='orders',
                                    to='wbportfolio.orderproposal'),
        ),
        migrations.AddField(
            model_name='order',
            name='import_source',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL,
                                    to='io.importsource'),
        ),
        migrations.AddField(
            model_name='order',
            name='portfolio',
            field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='%(class)ss',
                                    to='wbportfolio.portfolio', verbose_name='Portfolio'),
        ),
        migrations.AddField(
            model_name='order',
            name='underlying_instrument',
            field=models.ForeignKey(help_text='The instrument that is this transaction.',
                                    limit_choices_to=models.Q(('children__isnull', True)),
                                    on_delete=django.db.models.deletion.PROTECT, related_name='%(class)ss',
                                    to='wbfdm.instrument', verbose_name='Underlying Instrument'),
        ),
        migrations.RunSQL(
            sql="SET CONSTRAINTS ALL IMMEDIATE;",
        ),
        migrations.RunPython(migrate_order),
        migrations.RunSQL(
            sql="SET CONSTRAINTS ALL DEFERRED;",
        ),
        migrations.AlterModelOptions(
            name='trade',
            options={'verbose_name': 'Trade', 'verbose_name_plural': 'Trades'},
        ),
        migrations.RemoveConstraint(
            model_name='trade',
            name='unique_manual_trade',
        ),
        migrations.RemoveField(
            model_name='trade',
            name='drift_factor',
        ),
        migrations.RemoveField(
            model_name='trade',
            name='order',
        ),
        migrations.RemoveField(
            model_name='trade',
            name='order_proposal',
        ),
        migrations.AddIndex(
            model_name='order',
            index=models.Index(fields=['underlying_instrument', 'value_date'], name='wbportfolio_underly_051048_idx'),
        ),
        migrations.AddIndex(
            model_name='order',
            index=models.Index(fields=['portfolio', 'underlying_instrument', 'value_date'], name='wbportfolio_portfol_26d2a7_idx'),
        ),
        migrations.AddIndex(
            model_name='order',
            index=models.Index(fields=['order_proposal', 'underlying_instrument'], name='wbportfolio_order_p_637d28_idx'),
        ),
        migrations.AddConstraint(
            model_name='order',
            constraint=models.UniqueConstraint(fields=('order_proposal', 'underlying_instrument'), name='unique_order'),
        ),
        migrations.AlterField(
            model_name='orderproposal',
            name='comment',
            field=models.TextField(blank=True, default='', verbose_name='Order Comment'),
        ),
        migrations.RemoveField(
            model_name='order',
            name='drift_factor',
        ),
        migrations.AddField(
            model_name='order',
            name='daily_return',
            field=models.DecimalField(decimal_places=16, default=Decimal('0'), help_text='The Ex-Post daily return',
                                      max_digits=19, verbose_name='Daily Return'),
        ),
        migrations.AddIndex(
            model_name='order',
            index=models.Index(fields=['order_proposal'], name='wbportfolio_order_p_630213_idx'),
        ),
        migrations.RemoveField(
            model_name='order',
            name='status',
        ),
        migrations.RemoveField(
            model_name='trade',
            name='status',
        ),
        migrations.AlterField(
            model_name='orderproposal',
            name='status',
            field=django_fsm.FSMField(
                choices=[('DRAFT', 'Draft'), ('SUBMIT', 'Pending'), ('APPROVED', 'Approved'), ('DENIED', 'Denied'),
                         ('FAILED', 'Failed')], default='DRAFT', max_length=50, verbose_name='Status'),
        ),
    ]
