# Generated by Django 5.0.14 on 2025-06-17 13:58

import django.db.models.deletion
import django.db.models.expressions
import django.utils.timezone
from decimal import Decimal
from django.db import migrations, models
from django.db.migrations.operations.models import ModelOptionOperation
from django.db.models import Count


def remove_duplicate(apps, schema_editor):
    Trade = apps.get_model("wbportfolio", "Trade")
    for row in Trade.objects.filter(trade_proposal__isnull=False).values("underlying_instrument", "transaction_date", "portfolio").annotate(c=Count("*")).filter(c__gt=1):
        qs = Trade.objects.filter(underlying_instrument=row["underlying_instrument"], transaction_date=row["transaction_date"], portfolio=row["portfolio"])
        for t in qs[1:]:
            t.delete()

class SetModelBasesOptionOperation(ModelOptionOperation):
    """
    A migration operation that updates the bases of a model.
    This can be used to separate a model from its parent. Specifically
    when multi-table inheritance is used.
    """
    def __init__(self, name, bases):
        super().__init__(name)
        self.bases = bases

    def deconstruct(self):
        return (self.__class__.__qualname__, [], {"bases": self.bases})

    def state_forwards(self, app_label, state):
        model_state = state.models[app_label, self.name_lower]
        model_state.bases = self.bases
        state.reload_model(app_label, self.name_lower, delay=True)

    def database_forwards(self, app_label, schema_editor, from_state, to_state):
        pass

    def database_backwards(self, app_label, schema_editor, from_state, to_state):
        pass

    def describe(self):
        return "Update bases of the model %s" % self.name

    @property
    def migration_name_fragment(self):
        return "set_%s_bases" % self.name_lower

class Migration(migrations.Migration):

    dependencies = [
        ('currency', '0001_initial'),
        ('io', '0008_importsource_resource_kwargs'),
        ('wbfdm', '0030_alter_relatedinstrumentthroughmodel_related_type'),
        ('wbportfolio', '0076_alter_dividendtransaction_price_and_more'),
    ]

    operations = [
        migrations.AlterField(
            model_name='transaction',
            name='transaction_type',
            field=models.CharField(
                choices=[('Trade', 'Trade'), ('DividendTransaction', 'Dividend Transaction'), ('Fees', 'Fees')],
                default='Trade', max_length=255, verbose_name='Type'),
        ),
        migrations.DeleteModel(
            name='Expiry',
        ),
        migrations.RemoveIndex(
            model_name='fees',
            name='wbportfolio_linked__a49c5d_idx',
        ),
        migrations.RemoveIndex(
            model_name='fees',
            name='wbportfolio_transac_1f7a29_idx',
        ),
        migrations.RenameField(
            model_name='fees',
            old_name='linked_product',
            new_name='product',
        ),
        migrations.RenameField(
            model_name='trade',
            old_name='external_identifier2',
            new_name='external_id_alternative',
        ),
        SetModelBasesOptionOperation("Fees", (models.Model, )),
        SetModelBasesOptionOperation("Trade", (models.Model, )),
        SetModelBasesOptionOperation("DividendTransaction", (models.Model, )),
        migrations.RenameField(
            model_name='dividendtransaction',
            old_name='transaction_ptr',
            new_name='id',
        ),
        migrations.RenameField(
            model_name='fees',
            old_name='transaction_ptr',
            new_name='id',
        ),
        migrations.RenameField(
            model_name='trade',
            old_name='transaction_ptr',
            new_name='id',
        ),
        migrations.AlterField(
            model_name='dividendtransaction',
            name='id',
            field=models.AutoField(auto_created=True, primary_key=True, serialize=False,
                                   verbose_name='ID'),
        ),
        migrations.AlterField(
            model_name='fees',
            name='id',
            field=models.AutoField(auto_created=True, primary_key=True, serialize=False,
                                   verbose_name='ID'),
        ),
        migrations.AlterField(
            model_name='trade',
            name='id',
            field=models.AutoField(auto_created=True, primary_key=True, serialize=False,
                                   verbose_name='ID'),
        ),
        migrations.AlterField(
            model_name='dividendtransaction',
            name='price',
            field=models.DecimalField(decimal_places=4, help_text='The amount paid per share', max_digits=15,
                                      verbose_name='DPS'),
        ),
        migrations.AlterField(
            model_name='dividendtransaction',
            name='shares',
            field=models.DecimalField(decimal_places=4, default=Decimal('0.0'),
                                      help_text='The number of shares held at record date, used to calculate the dividend',
                                      max_digits=15, verbose_name='Shares / Quantity'),
        ),
        migrations.AlterField(
            model_name='fees',
            name='fee_date',
            field=models.DateField(help_text='The date that this fee was paid.', verbose_name='Fees Date'),
        ),


        migrations.AddField(
            model_name='dividendtransaction',
            name='comment',
            field=models.TextField(blank=True, default='', verbose_name='Comment'),
        ),
        migrations.AddField(
            model_name='dividendtransaction',
            name='created',
            field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='dividendtransaction',
            name='currency',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='%(class)ss', to='currency.currency', verbose_name='Currency'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='dividendtransaction',
            name='currency_fx_rate',
            field=models.DecimalField(decimal_places=8, default=Decimal('1'), max_digits=14, verbose_name='FOREX rate'),
        ),
        migrations.AddField(
            model_name='dividendtransaction',
            name='distribution_method',
            field=models.CharField(choices=[('Payment', 'Payment'), ('Reinvestment', 'Reinvestment')], default='Payment', max_length=255, verbose_name='Type'),
        ),
        migrations.AddField(
            model_name='dividendtransaction',
            name='ex_date',
            field=models.DateField(blank=True, null=True, help_text='The date on which the stock starts trading without the dividend', verbose_name='Ex-Dividend Date'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='dividendtransaction',
            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='dividendtransaction',
            name='portfolio',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='%(class)ss', to='wbportfolio.portfolio', verbose_name='Portfolio'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='dividendtransaction',
            name='record_date',
            field=models.DateField(blank=True, null=True, help_text='The date on which the holder must own the shares to be eligible for the dividend', verbose_name='Record Date'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='dividendtransaction',
            name='underlying_instrument',
            field=models.ForeignKey(blank=True, null=True, 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'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='dividendtransaction',
            name='updated',
            field=models.DateTimeField(auto_now=True),
        ),
        migrations.AddField(
            model_name='dividendtransaction',
            name='value_date',
            field=models.DateField(blank=True, null=True, help_text='The date that this transaction was valuated/paid.', verbose_name='Value Date'),
            preserve_default=False,
        ),

        migrations.AddField(
            model_name='fees',
            name='currency',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT,
                                    related_name='fees', to='currency.currency', verbose_name='Currency'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='fees',
            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='fees',
            name='currency_fx_rate',
            field=models.DecimalField(decimal_places=8, default=Decimal('1'), max_digits=14, verbose_name='FOREX rate'),
        ),
        migrations.AddField(
            model_name='fees',
            name='created',
            field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='fees',
            name='total_value',
            field=models.DecimalField(decimal_places=4, blank=True, null=True, max_digits=20, verbose_name='Total Value'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='fees',
            name='total_value_gross',
            field=models.DecimalField(decimal_places=4, blank=True, null=True, max_digits=20, verbose_name='Total Value Gross'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='fees',
            name='updated',
            field=models.DateTimeField(auto_now=True),
        ),


        migrations.AddField(
            model_name='trade',
            name='currency_fx_rate',
            field=models.DecimalField(decimal_places=8, default=Decimal('1'), max_digits=14, verbose_name='FOREX rate'),
        ),
        migrations.AddField(
            model_name='trade',
            name='book_date',
            field=models.DateField(blank=True, null=True, help_text='The date that this transaction was booked.', verbose_name='Trade Date'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='trade',
            name='comment',
            field=models.TextField(blank=True, default='', verbose_name='Comment'),
        ),
        migrations.AddField(
            model_name='trade',
            name='created',
            field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='trade',
            name='external_id',
            field=models.CharField(blank=True, help_text='An external identifier that was supplied.', max_length=255, null=True, verbose_name='External Identifier'),
        ),
        migrations.AddField(
            model_name='trade',
            name='transaction_date',
            field=models.DateField(blank=True, null=True, help_text='The date that this transaction was traded.', verbose_name='Trade Date'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='trade',
            name='updated',
            field=models.DateTimeField(auto_now=True),
        ),
        migrations.AddField(
            model_name='trade',
            name='value_date',
            field=models.DateField(blank=True, null=True, help_text='The date that this transaction was valuated/paid.', verbose_name='Value Date'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='trade',
            name='currency',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT,
                                    related_name='%(class)ss', to='currency.currency', verbose_name='Currency'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='trade',
            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='trade',
            name='portfolio',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT,
                                    related_name='%(class)ss', to='wbportfolio.portfolio', verbose_name='Portfolio'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='trade',
            name='underlying_instrument',
            field=models.ForeignKey(blank=True, null=True, 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'),
            preserve_default=False,
        ),


        migrations.RunSQL(
            """
            UPDATE wbportfolio_dividendtransaction AS o
            SET comment = t.comment, currency_id = t.currency_id, currency_fx_rate = t.currency_fx_rate, ex_date = t.transaction_date, import_source_id = t.import_source_id, portfolio_id = t.portfolio_id, record_date = t.transaction_date, underlying_instrument_id = t.underlying_instrument_id, value_date = t.value_date
            FROM wbportfolio_transaction AS t
            WHERE o.id = t.id
            """
        ),
        migrations.RunSQL(
            """
            UPDATE wbportfolio_fees AS o
            SET currency_id = t.currency_id, import_source_id = t.import_source_id, currency_fx_rate = t.currency_fx_rate, total_value = t.total_value, total_value_gross = t.total_value_gross
            FROM wbportfolio_transaction AS t
            WHERE o.id = t.id
            """
        ),
        migrations.RunSQL(
            """
            UPDATE wbportfolio_trade o
            SET underlying_instrument_id = t.underlying_instrument_id, portfolio_id = t.portfolio_id, currency_fx_rate = t.currency_fx_rate, book_date = t.book_date, comment = t.comment, external_id = t.external_id, transaction_date = t.transaction_date, value_date = t.value_date, currency_id = t.currency_id, import_source_id = t.import_source_id
            FROM wbportfolio_transaction AS t
            WHERE o.id = t.id
            """
        ),



        migrations.AlterField(
            model_name='dividendtransaction',
            name='currency',
            field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.PROTECT, related_name='%(class)ss',
                                    to='currency.currency', verbose_name='Currency'),
            preserve_default=False,
        ),
        migrations.AlterField(
            model_name='dividendtransaction',
            name='ex_date',
            field=models.DateField(default=None,
                                   help_text='The date on which the stock starts trading without the dividend',
                                   verbose_name='Ex-Dividend Date'),
            preserve_default=False,
        ),
        migrations.AlterField(
            model_name='dividendtransaction',
            name='portfolio',
            field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.PROTECT, related_name='%(class)ss',
                                    to='wbportfolio.portfolio', verbose_name='Portfolio'),
            preserve_default=False,
        ),
        migrations.AlterField(
            model_name='dividendtransaction',
            name='record_date',
            field=models.DateField(default=None,
                                   help_text='The date on which the holder must own the shares to be eligible for the dividend',
                                   verbose_name='Record Date'),
            preserve_default=False,
        ),
        migrations.AlterField(
            model_name='dividendtransaction',
            name='underlying_instrument',
            field=models.ForeignKey(default=None, 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'),
            preserve_default=False,
        ),
        migrations.AlterField(
            model_name='dividendtransaction',
            name='value_date',
            field=models.DateField(default=None, help_text='The date that this transaction was valuated/paid.',
                                   verbose_name='Value Date'),
            preserve_default=False,
        ),
        migrations.AlterField(
            model_name='fees',
            name='currency',
            field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.PROTECT, related_name='fees',
                                    to='currency.currency', verbose_name='Currency'),
            preserve_default=False,
        ),
        migrations.AlterField(
            model_name='fees',
            name='total_value',
            field=models.DecimalField(decimal_places=4, default=None, max_digits=20, verbose_name='Total Value'),
            preserve_default=False,
        ),
        migrations.AlterField(
            model_name='fees',
            name='total_value_gross',
            field=models.DecimalField(decimal_places=4, default=None, max_digits=20, verbose_name='Total Value Gross'),
            preserve_default=False,
        ),
        migrations.AlterField(
            model_name='fees',
            name='product',
            field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='fees',
                                    to='wbportfolio.product', verbose_name='Product'),
        ),
        migrations.AlterField(
            model_name='trade',
            name='book_date',
            field=models.DateField(default=None, help_text='The date that this transaction was booked.',
                                   verbose_name='Trade Date'),
            preserve_default=False,
        ),
        migrations.AlterField(
            model_name='trade',
            name='currency',
            field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.PROTECT, related_name='%(class)ss',
                                    to='currency.currency', verbose_name='Currency'),
            preserve_default=False,
        ),
        migrations.AlterField(
            model_name='trade',
            name='external_id_alternative',
            field=models.CharField(blank=True, help_text='A second external identifier that was supplied.',
                                   max_length=255, null=True, verbose_name='Alternative External Identifier'),
        ),
        migrations.AlterField(
            model_name='trade',
            name='portfolio',
            field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.PROTECT, related_name='%(class)ss',
                                    to='wbportfolio.portfolio', verbose_name='Portfolio'),
            preserve_default=False,
        ),
        migrations.AlterField(
            model_name='trade',
            name='transaction_date',
            field=models.DateField(default=None, help_text='The date that this transaction was traded.',
                                   verbose_name='Trade Date'),
            preserve_default=False,
        ),
        migrations.AlterField(
            model_name='trade',
            name='underlying_instrument',
            field=models.ForeignKey(default=None, 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'),
            preserve_default=False,
        ),
        migrations.AlterField(
            model_name='trade',
            name='value_date',
            field=models.DateField(default=None, help_text='The date that this transaction was valuated/paid.',
                                   verbose_name='Value Date'),
            preserve_default=False,
        ),

        migrations.AddField(
            model_name='dividendtransaction',
            name='fees',
            field=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)),
        ),
        migrations.AddField(
            model_name='dividendtransaction',
            name='total_value',
            field=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)),
        ),
        migrations.AddField(
            model_name='dividendtransaction',
            name='total_value_fx_portfolio',
            field=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)),
        ),
        migrations.AddField(
            model_name='dividendtransaction',
            name='total_value_gross',
            field=models.GeneratedField(db_persist=True, expression=django.db.models.expressions.CombinedExpression(
                django.db.models.expressions.CombinedExpression(models.F('price'), '*', models.F('shares')), '*',
                models.F('retrocession')), output_field=models.DecimalField(decimal_places=4, max_digits=20)),
        ),
        migrations.AddField(
            model_name='dividendtransaction',
            name='total_value_gross_fx_portfolio',
            field=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)),
        ),
        migrations.AddField(
            model_name='trade',
            name='total_value',
            field=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)),
        ),
        migrations.AddField(
            model_name='trade',
            name='total_value_gross',
            field=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)),
        ),
        migrations.AddField(
            model_name='trade',
            name='fees',
            field=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)),
        ),
        migrations.AddField(
            model_name='trade',
            name='total_value_fx_portfolio',
            field=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)),
        ),
        migrations.AddField(
            model_name='trade',
            name='total_value_gross_fx_portfolio',
            field=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)),
        ),
        migrations.AlterField(
            model_name='trade',
            name='price',
            field=models.DecimalField(decimal_places=4, help_text='The price per share.', max_digits=16,
                                      verbose_name='Price'),
        ),
        migrations.AddField(
            model_name='fees',
            name='total_value_fx_portfolio',
            field=models.GeneratedField(db_persist=True, expression=django.db.models.expressions.CombinedExpression(
                models.F('currency_fx_rate'), '*', models.F('total_value')),
                                        output_field=models.DecimalField(decimal_places=4, max_digits=20)),
        ),
        migrations.AddField(
            model_name='fees',
            name='total_value_gross_fx_portfolio',
            field=models.GeneratedField(db_persist=True, expression=django.db.models.expressions.CombinedExpression(
                models.F('currency_fx_rate'), '*', models.F('total_value_gross')),
                                        output_field=models.DecimalField(decimal_places=4, max_digits=20)),
        ),

        # cleanup
        migrations.RemoveField(
            model_name='transaction',
            name='currency',
        ),
        migrations.RemoveField(
            model_name='transaction',
            name='import_source',
        ),
        migrations.RemoveField(
            model_name='transaction',
            name='portfolio',
        ),
        migrations.RemoveField(
            model_name='transaction',
            name='underlying_instrument',
        ),
        migrations.DeleteModel(
            name='Transaction',
        ),
        migrations.AddIndex(
            model_name='fees',
            index=models.Index(fields=['product'], name='wbportfolio_product_daf107_idx'),
        ),
        migrations.AddIndex(
            model_name='fees',
            index=models.Index(fields=['transaction_subtype', 'product', 'fee_date', 'calculated'],
                               name='wbportfolio_transac_7355c2_idx'),
        ),
        migrations.AddIndex(
            model_name='trade',
            index=models.Index(fields=['underlying_instrument', 'transaction_date'],
                               name='wbportfolio_underly_a0f0ff_idx'),
        ),
        migrations.AddIndex(
            model_name='trade',
            index=models.Index(fields=['portfolio', 'underlying_instrument', 'transaction_date'],
                               name='wbportfolio_portfol_6a42a2_idx'),
        ),
        migrations.RunPython(remove_duplicate),
        migrations.AddConstraint(
            model_name='trade',
            constraint=models.UniqueConstraint(condition=models.Q(('trade_proposal__isnull', False)),
                                               fields=('portfolio', 'transaction_date', 'underlying_instrument'),
                                               name='unique_manual_trade'),
        ),
    ]
