# Generated by Django 4.2.7 on 2023-11-27 09:43

import colorfield.fields
import django.contrib.postgres.fields
import django.core.validators
import django.db.models.deletion
import django_better_admin_arrayfield.models.fields
import django_fsm
import mptt.fields
import wbcore.models.fields
from django.apps import apps
from django.db import migrations, models
from wbfdm.models.instruments.mixin.financials_computed import (
    InstrumentPriceComputedMixin,
)

state_operations = [
    migrations.CreateModel(
        name="Classification",
        fields=[
            (
                "id",
                models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID"),
            ),
            ("computed_str", models.CharField(blank=True, max_length=512, null=True, verbose_name="Name")),
            (
                "height",
                models.PositiveIntegerField(default=0, verbose_name="The height (leaf node have height 0)"),
            ),
            (
                "level_representation",
                models.CharField(max_length=256, verbose_name="Level Representation"),
            ),
            ("name", models.CharField(max_length=128, verbose_name="Name")),
            ("code_aggregated", models.CharField(max_length=64, verbose_name="Code Aggregated")),
            (
                "investable",
                models.BooleanField(default=True, help_text="Is this classification investable for us?"),
            ),
            (
                "description",
                models.TextField(
                    blank=True,
                    default="",
                    help_text="Give a basic definition and description",
                    verbose_name="Definition/Description",
                ),
            ),
            ("lft", models.PositiveIntegerField(editable=False)),
            ("rght", models.PositiveIntegerField(editable=False)),
            ("tree_id", models.PositiveIntegerField(db_index=True, editable=False)),
            ("level", models.PositiveIntegerField(editable=False)),
        ],
        options={
            "verbose_name": "Classification",
            "verbose_name_plural": "Classifications",
        },
    ),
    migrations.CreateModel(
        name="ClassificationGroup",
        fields=[
            (
                "id",
                models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID"),
            ),
            ("name", models.CharField(max_length=128, verbose_name="Name")),
            (
                "is_primary",
                models.BooleanField(
                    default=False,
                    help_text="Set to True if this classification must be used as default if not specified otherwise",
                    verbose_name="Primary",
                ),
            ),
            ("max_depth", models.IntegerField(default=0, verbose_name="Maximum Depth")),
            (
                "code_level_digits",
                models.IntegerField(default=2, verbose_name="The number of digits per code level"),
            ),
        ],
        options={
            "verbose_name": "Classification Group",
            "verbose_name_plural": "Classification Groups",
        },
    ),
    migrations.CreateModel(
        name="Deal",
        fields=[
            (
                "id",
                models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID"),
            ),
            (
                "type",
                models.CharField(
                    choices=[
                        ("DEAL", "Deal"),
                        ("FUNDING", "Funding"),
                        ("INVESTMENT", "Investment"),
                        ("PORTFOLIO_EXIT", "Portfolio Exit"),
                    ],
                    default="DEAL",
                    help_text="The deal type",
                    max_length=14,
                    verbose_name="Type",
                ),
            ),
            ("external_id", models.CharField(blank=True, max_length=64, null=True)),
            ("date", models.DateField()),
            ("transaction_amount", models.FloatField(help_text="Deal Size (in millions")),
            ("funding_round", models.CharField(max_length=128, verbose_name="Funding Round")),
            (
                "funding_round_category",
                models.CharField(max_length=128, verbose_name="Funding Round Category"),
            ),
            (
                "valuation",
                models.FloatField(
                    blank=True,
                    help_text="Valuation of the funded organization after this transaction (in Millions USD).",
                    null=True,
                    verbose_name="Valuaton",
                ),
            ),
            (
                "valuation_estimated",
                models.BooleanField(
                    default=False,
                    help_text="True if the valuation is an estimate",
                    verbose_name="Is valuation estimated",
                ),
            ),
            (
                "valuation_source_type",
                models.CharField(blank=True, help_text="The source type of the valuation", max_length=24, null=True),
            ),
            (
                "valuation_media_mention_source_urls",
                django.contrib.postgres.fields.ArrayField(
                    base_field=models.URLField(),
                    blank=True,
                    help_text="List of URLs used to source the valuation for the Media Mentions source type.",
                    null=True,
                    size=None,
                ),
            ),
        ],
        options={
            "abstract": False,
        },
        bases=(models.Model,),
    ),
    migrations.CreateModel(
        name="Exchange",
        fields=[
            (
                "id",
                models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID"),
            ),
            (
                "name",
                models.CharField(
                    blank=True,
                    help_text="Name of the Exchange.",
                    max_length=265,
                    null=True,
                    verbose_name="Exchange Name",
                ),
            ),
            (
                "opening_time",
                models.TimeField(
                    blank=True,
                    help_text="The opening time of the exchange",
                    null=True,
                    verbose_name="Exchange Opening time",
                ),
            ),
            (
                "closing_time",
                models.TimeField(
                    blank=True,
                    help_text="The closing time of the exchange",
                    null=True,
                    verbose_name="Exchange Closing time",
                ),
            ),
            (
                "mic_code",
                models.CharField(
                    blank=True,
                    help_text="Market Identifier Code.",
                    max_length=4,
                    null=True,
                    unique=True,
                    verbose_name="MIC (ISO)",
                ),
            ),
            (
                "mic_name",
                models.CharField(
                    blank=True,
                    help_text="Market Identifier Name.",
                    max_length=126,
                    null=True,
                    verbose_name="MIC (ISO) Name",
                ),
            ),
            (
                "operating_mic_code",
                models.CharField(
                    blank=True,
                    help_text="Operating Market Identifier Code.",
                    max_length=4,
                    null=True,
                    verbose_name="Operating MIC Code",
                ),
            ),
            (
                "operating_mic_name",
                models.CharField(
                    blank=True,
                    help_text="Operating Market Identifier Name.",
                    max_length=126,
                    null=True,
                    verbose_name="Operating MIC Name",
                ),
            ),
            (
                "bbg_exchange",
                models.CharField(
                    blank=True,
                    help_text="Bloomberg Exchange Code.",
                    max_length=4,
                    null=True,
                    verbose_name="BBG Exchange Code",
                ),
            ),
            (
                "bbg_composite_primary",
                models.BooleanField(
                    default=False,
                    help_text="Indicates the primary exchange for this BBG Composite Code.",
                    verbose_name="BBG Primary composite",
                ),
            ),
            (
                "bbg_composite",
                models.CharField(
                    blank=True,
                    help_text="Bloomberg Composite Code.",
                    max_length=4,
                    null=True,
                    verbose_name="BBG Composite Code",
                ),
            ),
            (
                "refinitiv_identifier_code",
                models.CharField(
                    blank=True,
                    help_text="Reuters Exchange Code.",
                    max_length=4,
                    null=True,
                    verbose_name="RIC Exchange Code",
                ),
            ),
            (
                "refinitiv_mnemonic",
                models.CharField(
                    blank=True,
                    help_text="Reuters Exchange Mnemonic Code.",
                    max_length=4,
                    null=True,
                    verbose_name="Refinitiv Mnemonic",
                ),
            ),
            (
                "website",
                models.URLField(
                    blank=True, help_text="The Website of the Exchange", null=True, verbose_name="Website"
                ),
            ),
            (
                "comments",
                models.TextField(
                    blank=True,
                    default="",
                    help_text="Any comments for this exchange",
                    verbose_name="Comments",
                ),
            ),
        ],
        options={
            "verbose_name": "Exchange",
            "verbose_name_plural": "Exchanges",
        },
    ),
    migrations.CreateModel(
        name="InstrumentClassificationRelatedInstrument",
        fields=[
            (
                "id",
                models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID"),
            ),
            (
                "related_instrument_type",
                models.CharField(
                    blank=True,
                    choices=[
                        ("PARTNER", "Partner"),
                        ("SUPPLIER", "Supplier"),
                        ("PEER", "Peer"),
                        ("COMPETITOR", "Competitor"),
                        ("BIGGEST_THREAT", "Biggest Threat"),
                        ("CUSTOMER", "Customer"),
                    ],
                    max_length=16,
                    null=True,
                ),
            ),
        ],
    ),
    migrations.CreateModel(
        name="InstrumentClassificationThroughModel",
        fields=[
            (
                "id",
                models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID"),
            ),
            ("tag_detail_endpoint", models.CharField(blank=True, max_length=255, null=True)),
            ("tag_representation", models.CharField(blank=True, max_length=512, null=True)),
            ("is_favorite", models.BooleanField(default=False)),
            ("reason", models.TextField(blank=True, default="", verbose_name="Reason for the choice")),
            (
                "pure_player",
                models.BooleanField(default=False, help_text="Pure Players Companies", verbose_name="Pure Player"),
            ),
            (
                "top_player",
                models.BooleanField(default=False, help_text="Top Players Companies", verbose_name="Top Player"),
            ),
            (
                "percent_of_revenue",
                models.DecimalField(
                    blank=True,
                    decimal_places=4,
                    max_digits=5,
                    null=True,
                    validators=[
                        django.core.validators.MinValueValidator(0),
                        django.core.validators.MaxValueValidator(1),
                    ],
                    verbose_name="% of revenue",
                ),
            ),
        ],
    ),
    migrations.CreateModel(
        name="InstrumentFavoriteGroup",
        fields=[
            (
                "id",
                models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID"),
            ),
            ("name", models.CharField(max_length=256)),
            (
                "public",
                models.BooleanField(
                    default=False, help_text="If set to True, this group will be available to everyone."
                ),
            ),
            (
                "primary",
                models.BooleanField(
                    default=False,
                    help_text="If set to True, this group will be set as default filter for instrument based viewset (Only one primary group allowed).",
                ),
            ),
        ],
        options={
            "abstract": False,
        },
    ),
    migrations.CreateModel(
        name="InstrumentList",
        fields=[
            (
                "id",
                models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID"),
            ),
            ("name", models.CharField(max_length=255)),
            ("identifier", models.CharField(blank=True, max_length=255, unique=True)),
            (
                "instrument_list_type",
                models.CharField(
                    blank=True,
                    choices=[("WATCH", "Watch List"), ("EXCLUSION", "Exclusion List")],
                    max_length=32,
                    null=True,
                ),
            ),
        ],
        options={
            "verbose_name": "Instrument List",
            "verbose_name_plural": "Instrument Lists",
            "permissions": (("administrate_instrumentlist", "Can administrate Instrument List"),),
        },
    ),
    migrations.CreateModel(
        name="InstrumentListThroughModel",
        fields=[
            (
                "id",
                models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID"),
            ),
            ("computed_str", models.CharField(blank=True, max_length=512, null=True, verbose_name="Name")),
            ("instrument_str", models.CharField(max_length=256)),
            ("from_date", models.DateField(blank=True, null=True)),
            ("to_date", models.DateField(blank=True, null=True)),
            ("comment", models.TextField(blank=True, default="")),
            ("validated", models.BooleanField(default=False)),
        ],
        options={
            "verbose_name": "Instrument in Instrument List",
            "notification_types": [
                (
                    "wbfdm.instrument_list_add",
                    "Instrument added to Instrument List",
                    "A notification when an instrument gets added to a list.",
                    True,
                    True,
                    True,
                )
            ],
        },
        bases=(models.Model,),
    ),
    migrations.CreateModel(
        name="InstrumentRequest",
        fields=[
            (
                "id",
                models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID"),
            ),
            (
                "instrument_type",
                models.CharField(
                    choices=[
                        ("ADR", "American Depository Receipt (ADR)"),
                        ("CF", "Close Ended Fund"),
                        ("EQ", "Equity"),
                        ("ETF", "Exchange Traded Fund"),
                        ("ETC", "Exchange Traded Commodity"),
                        ("ETN", "Exchange Traded Note"),
                        ("WARRANT", "Warrant"),
                        ("GDR", "Global Depository Receipt (GDR)"),
                        ("GS", "Genussschein"),
                        ("TRUST", "Investment Trust"),
                        ("NVDR", "Non-voting depository receipt (NVDR)"),
                        ("PREF", "Preference Share"),
                        ("COMP", "Company"),
                        ("QT", "Quote"),
                    ],
                    max_length=255,
                    verbose_name="Type",
                ),
            ),
            (
                "status",
                django_fsm.FSMField(
                    choices=[
                        ("PENDING", "Pending"),
                        ("APPROVED", "Approved"),
                        ("DENIED", "Denied"),
                        ("DRAFT", "Draft"),
                    ],
                    default="DRAFT",
                    help_text="The Request Status (default to Pending)",
                    max_length=50,
                    verbose_name="Status",
                ),
            ),
            ("notes", models.TextField(blank=True, null=True, verbose_name="Notes")),
            (
                "created",
                models.DateTimeField(auto_now_add=True, help_text="The request creation time", verbose_name="Created"),
            ),
            ("instrument_data", models.JSONField(default=dict, verbose_name="Instrument Data")),
        ],
        options={
            "abstract": False,
        },
    ),
    migrations.CreateModel(
        name="RelatedInstrumentThroughModel",
        fields=[
            (
                "id",
                models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID"),
            ),
            ("is_primary", models.BooleanField(default=False)),
            (
                "related_type",
                models.CharField(
                    choices=[
                        ("BENCHMARK", "Benchmark"),
                        ("PEER", "Peer"),
                        ("RISK_INSTRUMENT", "Risk Instrument"),
                    ],
                    default="BENCHMARK",
                    max_length=32,
                ),
            ),
        ],
    ),
    migrations.CreateModel(
        name="Cash",
        fields=[],
        options={
            "proxy": True,
            "indexes": [],
            "constraints": [],
        },
        bases=("wbfdm.instrument",),
    ),
    migrations.CreateModel(
        name="InstrumentPrice",
        fields=[
            (
                "id",
                models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID"),
            ),
            (
                "lock_all_dynamic_fields",
                models.BooleanField(default=False, help_text="If True, will not allow dynamic fields to be updated"),
            ),
            (
                "locked_dynamic_fields",
                django_better_admin_arrayfield.models.fields.ArrayField(
                    base_field=models.CharField(max_length=128), blank=True, default=list, size=None
                ),
            ),
            ("updated_at", models.DateTimeField(auto_now=True)),
            ("date", models.DateField(verbose_name="Date")),
            ("calculated", models.BooleanField(default=False, verbose_name="Is Calculated")),
            (
                "net_value",
                models.DecimalField(decimal_places=6, max_digits=16, verbose_name="Value (Net)"),
            ),
            (
                "gross_value",
                wbcore.models.fields.DynamicDecimalField(
                    blank=True, decimal_places=6, max_digits=16, null=True, verbose_name="Value (Gross)"
                ),
            ),
            (
                "outstanding_shares",
                wbcore.models.fields.DynamicDecimalField(
                    blank=True,
                    decimal_places=4,
                    help_text="The amount of outstanding share for this instrument",
                    max_digits=16,
                    null=True,
                    verbose_name="Outstanding Shares",
                ),
            ),
            (
                "outstanding_shares_consolidated",
                wbcore.models.fields.DynamicDecimalField(
                    blank=True,
                    decimal_places=4,
                    help_text="The amount of outstanding share for this instrument",
                    max_digits=16,
                    null=True,
                    verbose_name="Outstanding Shares (Consolidated)",
                ),
            ),
            (
                "volume",
                models.FloatField(
                    blank=True,
                    help_text="The Volume of the Asset on the price date of the Asset.",
                    null=True,
                    verbose_name="Volume",
                ),
            ),
            (
                "volume_50d",
                wbcore.models.fields.DynamicFloatField(
                    blank=True,
                    help_text="The Average Volume of the Asset over the last 50 days from the price date of the Asset.",
                    null=True,
                    verbose_name="Average Volume (50 Days)",
                ),
            ),
            (
                "volume_200d",
                wbcore.models.fields.DynamicFloatField(
                    blank=True,
                    help_text="The Average Volume of the Asset over the last 200 days from the price date of the Asset.",
                    null=True,
                    verbose_name="Average Volume (200 Days)",
                ),
            ),
            (
                "market_capitalization",
                models.FloatField(
                    blank=True,
                    help_text="The Market Capitalization of the Asset the price date of the Asset.",
                    null=True,
                    verbose_name="Market Capitalization",
                ),
            ),
            (
                "market_capitalization_consolidated",
                wbcore.models.fields.DynamicFloatField(
                    blank=True,
                    help_text="the consolidated market value of a company in local currency.",
                    null=True,
                    verbose_name="Market Capitalization (Consolidated)",
                ),
            ),
            (
                "lock_statistics",
                models.BooleanField(
                    default=False,
                    help_text="If True, a save will not override the beta, correlation and sharpe ratio",
                ),
            ),
            ("sharpe_ratio", models.FloatField(blank=True, null=True, verbose_name="Sharpe Ratio")),
            ("correlation", models.FloatField(blank=True, null=True, verbose_name="Correlation")),
            ("beta", models.FloatField(blank=True, null=True, verbose_name="Beta")),
            (
                "currency_fx_rate_to_usd",
                models.ForeignKey(
                    blank=True,
                    help_text="Rate to between instrument currency and USD",
                    null=True,
                    on_delete=django.db.models.deletion.PROTECT,
                    related_name="instrument_prices",
                    to="currency.currencyfxrates",
                    verbose_name="Instrument Currency Rate",
                ),
            ),
            (
                "import_source",
                models.ForeignKey(
                    blank=True,
                    null=True,
                    on_delete=django.db.models.deletion.SET_NULL,
                    to="io.importsource",
                ),
            ),
            (
                "instrument",
                models.ForeignKey(
                    blank=True,
                    null=True,
                    on_delete=django.db.models.deletion.PROTECT,
                    related_name="prices",
                    to="wbfdm.instrument",
                    verbose_name="Instrument",
                ),
            ),
        ],
        options={
            "verbose_name": "Instrument Price",
            "verbose_name_plural": "Instrument Prices",
            "indexes": [
                models.Index(fields=["calculated", "date", "instrument"], name="fdm_instrumentprice_base_idx"),
                models.Index(fields=["calculated", "instrument"], name="fdm_instrumentprice_idx1"),
                models.Index(fields=["instrument"], name="fdm_instrumentprice_idx2"),
            ],
        },
        bases=(
            InstrumentPriceComputedMixin,
            models.Model,
        ),
    ),
    migrations.AddField(
        model_name="instrument",
        name="additional_urls",
        field=django.contrib.postgres.fields.ArrayField(
            base_field=models.URLField(blank=True, null=True), blank=True, default=list, size=None
        ),
    ),
    migrations.AddField(
        model_name="instrument",
        name="alternative_names",
        field=django.contrib.postgres.fields.ArrayField(
            base_field=models.CharField(blank=True, max_length=255, null=True), default=list, size=None
        ),
    ),
    migrations.AddField(
        model_name="instrument",
        name="computed_str",
        field=models.CharField(blank=True, max_length=512, null=True, verbose_name="Name"),
    ),
    migrations.AddField(
        model_name="instrument",
        name="founded_year",
        field=models.IntegerField(blank=True, null=True, verbose_name="Founded Year"),
    ),
    migrations.AddField(
        model_name="instrument",
        name="headquarter_address",
        field=models.CharField(blank=True, help_text="The company Headquarter address", max_length=512, null=True),
    ),
    migrations.AddField(
        model_name="instrument",
        name="headquarter_city",
        field=models.ForeignKey(
            blank=True,
            help_text="The company's headquarter city",
            limit_choices_to={"level": 3},
            null=True,
            on_delete=django.db.models.deletion.SET_NULL,
            related_name="headquarters_of",
            to="geography.geography",
            verbose_name="Headquarter City",
        ),
    ),
    migrations.AddField(
        model_name="instrument",
        name="identifier",
        field=models.CharField(blank=True, max_length=255, null=True, verbose_name="Identifier"),
    ),
    migrations.AddField(
        model_name="instrument",
        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="instrument",
        name="is_cash",
        field=models.BooleanField(default=False),
    ),
    migrations.AddField(
        model_name="instrument",
        name="isin",
        field=models.CharField(
            blank=True,
            help_text="The ISIN provided by the bank.",
            max_length=12,
            null=True,
            unique=True,
            verbose_name="ISIN",
        ),
    ),
    migrations.AddField(
        model_name="instrument",
        name="last_update",
        field=models.DateTimeField(auto_now=True, null=True),
    ),
    migrations.AddField(
        model_name="instrument",
        name="name_repr",
        field=models.CharField(blank=True, max_length=255, null=True, verbose_name="Name (Representation)"),
    ),
    migrations.AddField(
        model_name="instrument",
        name="old_isins",
        field=django.contrib.postgres.fields.ArrayField(
            base_field=models.CharField(max_length=12),
            blank=True,
            default=list,
            help_text="These old ISINs are stored for this instrument to retrieve it more easily later.",
            size=None,
            verbose_name="Old ISINS",
        ),
    ),
    migrations.AddField(
        model_name="instrument",
        name="primary_url",
        field=models.URLField(blank=True, help_text="The Company website url", null=True),
    ),
    migrations.AddField(
        model_name="instrument",
        name="refinitiv_identifier_code",
        field=models.CharField(
            blank=True,
            help_text="Refinitiv Identifier Code",
            max_length=255,
            null=True,
            unique=True,
            verbose_name="RIC",
        ),
    ),
    migrations.AddField(
        model_name="instrument",
        name="refinitiv_mnemonic_code",
        field=models.CharField(
            blank=True,
            help_text="Refinitiv Datastream Mnemonic Code",
            max_length=255,
            null=True,
            unique=True,
            verbose_name="Refinitiv Datastream Mnemonic Code",
        ),
    ),
    migrations.AddField(
        model_name="instrument",
        name="refinitiv_ticker",
        field=models.CharField(
            blank=True,
            help_text="Refinitiv Refinitiv",
            max_length=255,
            null=True,
            unique=True,
            verbose_name="Refinitiv Ticker",
        ),
    ),
    migrations.AddField(
        model_name="instrument",
        name="sedol",
        field=models.CharField(
            blank=True,
            help_text="Stock Exchange Daily Official List",
            max_length=255,
            null=True,
            unique=True,
            verbose_name="SEDOL",
        ),
    ),
    migrations.AddField(
        model_name="instrument",
        name="tag_detail_endpoint",
        field=models.CharField(blank=True, max_length=255, null=True),
    ),
    migrations.AddField(
        model_name="instrument",
        name="tag_representation",
        field=models.CharField(blank=True, max_length=512, null=True),
    ),
    migrations.AddField(
        model_name="instrument",
        name="tags",
        field=models.ManyToManyField(blank=True, related_name="%(app_label)s_%(class)s_items", to="tags.tag"),
    ),
    migrations.AddField(
        model_name="instrument",
        name="ticker",
        field=models.CharField(
            blank=True,
            help_text="The Bloomberg ticker without the exchange (e.g. AAPL)",
            max_length=255,
            null=True,
            verbose_name="Ticker Bloomberg",
        ),
    ),
    migrations.AddField(
        model_name="instrument",
        name="valoren",
        field=models.CharField(
            blank=True,
            help_text="Valoren Number",
            max_length=255,
            null=True,
            unique=True,
            verbose_name="Valoren Number",
        ),
    ),
    migrations.AddField(
        model_name="relatedinstrumentthroughmodel",
        name="instrument",
        field=models.ForeignKey(
            on_delete=django.db.models.deletion.CASCADE,
            related_name="related_instruments_through",
            to="wbfdm.instrument",
        ),
    ),
    migrations.AddField(
        model_name="relatedinstrumentthroughmodel",
        name="related_instrument",
        field=models.ForeignKey(
            on_delete=django.db.models.deletion.CASCADE,
            related_name="dependent_instruments_through",
            to="wbfdm.instrument",
        ),
    ),
    migrations.AddField(
        model_name="instrumentrequest",
        name="created_instrument",
        field=models.OneToOneField(
            blank=True,
            null=True,
            on_delete=django.db.models.deletion.CASCADE,
            related_name="creation_request",
            to="wbfdm.instrument",
        ),
    ),
    migrations.AddField(
        model_name="instrumentrequest",
        name="handler",
        field=models.ForeignKey(
            blank=True,
            null=True,
            on_delete=django.db.models.deletion.SET_NULL,
            related_name="handled_instrument_requests",
            to="directory.person",
            verbose_name="Handler",
        ),
    ),
    migrations.AddField(
        model_name="instrumentrequest",
        name="requester",
        field=models.ForeignKey(
            blank=True,
            null=True,
            on_delete=django.db.models.deletion.SET_NULL,
            related_name="instrument_requests",
            to="directory.person",
            verbose_name="Requester",
        ),
    ),
    migrations.AddField(
        model_name="instrumentlistthroughmodel",
        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="instrumentlistthroughmodel",
        name="instrument",
        field=models.ForeignKey(
            blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to="wbfdm.instrument"
        ),
    ),
    migrations.AddField(
        model_name="instrumentlistthroughmodel",
        name="instrument_list",
        field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="wbfdm.instrumentlist"),
    ),
    migrations.AddField(
        model_name="instrumentfavoritegroup",
        name="instruments",
        field=models.ManyToManyField(
            blank=True,
            related_name="favorite_groups",
            to="wbfdm.instrument",
            verbose_name="Favorite Instruments Group",
        ),
    ),
    migrations.AddField(
        model_name="instrumentfavoritegroup",
        name="owner",
        field=models.ForeignKey(
            blank=True,
            null=True,
            on_delete=django.db.models.deletion.CASCADE,
            related_name="favorite_instruments_groups",
            to="directory.person",
        ),
    ),
    migrations.AddField(
        model_name="instrumentclassificationthroughmodel",
        name="classification",
        field=models.ForeignKey(
            on_delete=django.db.models.deletion.CASCADE,
            related_name="instruments_through",
            to="wbfdm.classification",
        ),
    ),
    migrations.AddField(
        model_name="instrumentclassificationthroughmodel",
        name="instrument",
        field=models.ForeignKey(
            on_delete=django.db.models.deletion.CASCADE,
            related_name="classifications_through",
            to="wbfdm.instrument",
        ),
    ),
    migrations.AddField(
        model_name="instrumentclassificationthroughmodel",
        name="related_instruments",
        field=models.ManyToManyField(
            blank=True, through="wbfdm.InstrumentClassificationRelatedInstrument", to="wbfdm.instrument"
        ),
    ),
    migrations.AddField(
        model_name="instrumentclassificationthroughmodel",
        name="tags",
        field=models.ManyToManyField(blank=True, related_name="%(app_label)s_%(class)s_items", to="tags.tag"),
    ),
    migrations.AddField(
        model_name="instrumentclassificationrelatedinstrument",
        name="classified_instrument",
        field=models.ForeignKey(
            on_delete=django.db.models.deletion.CASCADE,
            related_name="related_instruements",
            to="wbfdm.instrumentclassificationthroughmodel",
        ),
    ),
    migrations.AddField(
        model_name="instrumentclassificationrelatedinstrument",
        name="related_instrument",
        field=models.ForeignKey(
            on_delete=django.db.models.deletion.CASCADE,
            related_name="instrument_classification_related",
            to="wbfdm.instrument",
        ),
    ),
    migrations.AddField(
        model_name="exchange",
        name="city",
        field=models.ForeignKey(
            blank=True,
            help_text="The city where this Exchange is located at.",
            limit_choices_to={"level": 3},
            null=True,
            on_delete=django.db.models.deletion.PROTECT,
            related_name="portfolio_exchanges_city",
            to="geography.geography",
            verbose_name="City",
        ),
    ),
    migrations.AddField(
        model_name="exchange",
        name="country",
        field=models.ForeignKey(
            blank=True,
            limit_choices_to={"level": 1},
            null=True,
            on_delete=django.db.models.deletion.SET_NULL,
            to="geography.geography",
        ),
    ),
    migrations.AddField(
        model_name="deal",
        name="equity",
        field=models.ForeignKey(
            on_delete=django.db.models.deletion.CASCADE, related_name="deals", to="wbfdm.instrument"
        ),
    ),
    migrations.AddField(
        model_name="deal",
        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="deal",
        name="investors",
        field=models.ManyToManyField(
            blank=True,
            help_text="Investors",
            related_name="invested_deals",
            to="wbfdm.instrument",
            verbose_name="Investors",
        ),
    ),
    migrations.AddField(
        model_name="classification",
        name="group",
        field=models.ForeignKey(
            on_delete=django.db.models.deletion.CASCADE,
            related_name="classifications",
            to="wbfdm.classificationgroup",
            verbose_name="Classification Group",
        ),
    ),
    migrations.AddField(
        model_name="classification",
        name="parent",
        field=mptt.fields.TreeForeignKey(
            blank=True,
            null=True,
            on_delete=django.db.models.deletion.CASCADE,
            related_name="children",
            to="wbfdm.classification",
            verbose_name="Parent Classification",
        ),
    ),
    migrations.AddField(
        model_name="instrument",
        name="classifications",
        field=models.ManyToManyField(
            blank=True,
            limit_choices_to=models.Q(("level", models.F("group__max_depth"))),
            related_name="instruments",
            through="wbfdm.InstrumentClassificationThroughModel",
            to="wbfdm.classification",
            verbose_name="Classifications",
        ),
    ),
    migrations.AddField(
        model_name="instrument",
        name="exchange",
        field=models.ForeignKey(
            blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to="wbfdm.exchange"
        ),
    ),
    migrations.AddField(
        model_name="instrument",
        name="related_instruments",
        field=models.ManyToManyField(
            blank=True,
            related_name="benchmarks_of",
            through="wbfdm.RelatedInstrumentThroughModel",
            to="wbfdm.instrument",
            verbose_name="The Related Instruments",
        ),
    ),
    migrations.AddField(
        model_name="instrument",
        name="base_color",
        field=colorfield.fields.ColorField(
            blank=True, default="#FF0000", image_field=None, max_length=64, null=True, samples=None
        ),
    ),
    migrations.AddField(
        model_name="instrument",
        name="issue_price",
        field=models.PositiveIntegerField(
            default=100,
            help_text="The initial issue price that is displayed on the factsheet",
            verbose_name="Issue Price",
        ),
    ),
    migrations.AddField(
        model_name="instrument",
        name="last_valuation_date",
        field=models.DateField(
            blank=True, help_text="Last Valuation Date", null=True, verbose_name="Last Valuation Date"
        ),
    ),
    migrations.AlterUniqueTogether(
        name="relatedinstrumentthroughmodel",
        unique_together={("instrument", "related_instrument", "is_primary", "related_type")},
    ),
    migrations.AddConstraint(
        model_name="instrumentclassificationthroughmodel",
        constraint=models.UniqueConstraint(
            fields=("instrument", "classification"), name="unique_classifiedinstruments"
        ),
    ),
    migrations.AddConstraint(
        model_name="instrumentprice",
        constraint=models.CheckConstraint(
            check=models.Q(("date__week_day__in", [1, 7]), _negated=True),
            name="wbfdm_instrumentprice_weekday_constraint",
        ),
    ),
    migrations.AddField(
        model_name="exchange",
        name="source",
        field=models.CharField(blank=True, max_length=64, null=True),
    ),
    migrations.AddField(
        model_name="exchange",
        name="source_id",
        field=models.CharField(blank=True, max_length=64, null=True),
    ),
    migrations.AlterField(
        model_name="instrumentrequest",
        name="instrument_type",
        field=models.CharField(
            choices=[
                ("ADR", "American Depository Receipt (ADR)"),
                ("CF", "Close Ended Fund"),
                ("EQ", "Equity"),
                ("ETF", "Exchange Traded Fund"),
                ("ETC", "Exchange Traded Commodity"),
                ("ETN", "Exchange Traded Note"),
                ("WARRANT", "Warrant"),
                ("GDR", "Global Depository Receipt (GDR)"),
                ("GS", "Genussschein"),
                ("TRUST", "Investment Trust"),
                ("NVDR", "Non-voting depository receipt (NVDR)"),
                ("PREF", "Preference Share"),
                ("COMP", "Company"),
                ("QT", "Quote"),
                ("Product", "Product"),
                ("Index", "Index"),
                ("ProductGroup", "Product Group"),
                ("Cash", "Cash"),
            ],
            max_length=255,
            verbose_name="Type",
        ),
    ),
    migrations.AddIndex(
        model_name="exchange",
        index=models.Index(fields=["source_id", "source"], name="wbfdm_excha_source__802ad7_idx"),
    ),
]


def get_operations():
    if apps.is_installed("wbportfolio"):
        return [
            migrations.RunSQL(
                sql='DROP TABLE "wbfdm_instrument" CASCADE',
                reverse_sql=migrations.RunSQL.noop,
            ),
            migrations.SeparateDatabaseAndState(state_operations=state_operations),
        ]
    return state_operations


def save_pms_instrument_id(apps, schema_editor):
    InstrumentLookup = apps.get_model("wbfdm", "InstrumentLookup")
    if apps.is_installed("wbportfolio"):
        for lp in InstrumentLookup.objects.filter(
            backend_path="wbfdm.contrib.dsws.backends.market_data.DSWSMarketDataBackend"
        ):
            try:
                lp.pms_instrument_id = lp.instrument.pms_instrument.id
                lp.save()
            except Exception:
                pass


class Migration(migrations.Migration):
    dependencies = [
        ("directory", "0006_employeremployeerelationship_position_name"),
        ("geography", "0001_initial"),
        ("tags", "0001_initial"),
        ("io", "0002_importsource_creator"),
        ("wbfdm", "0009_alter_controversy_flag_alter_controversy_initiated_and_more"),
    ]

    operations = [
        migrations.RemoveField(
            model_name="instrumentidentifier",
            name="instrument",
        ),
        migrations.AlterModelOptions(
            name="instrument",
            options={
                "permissions": (("administrate_instrument", "Can administrate Instrument"),),
                "verbose_name": "Instrument",
                "verbose_name_plural": "Instruments",
            },
        ),
        migrations.AddField(
            model_name="instrumentlookup",
            name="pms_instrument_id",
            field=models.IntegerField(blank=True, null=True),
        ),
        migrations.RunPython(save_pms_instrument_id),
        migrations.RemoveField(
            model_name="instrument",
            name="bbg_lookup",
        ),
        migrations.RemoveField(
            model_name="instrument",
            name="corporate_action_backend",
        ),
        migrations.RemoveField(
            model_name="instrument",
            name="esg_backend",
        ),
        migrations.RemoveField(
            model_name="instrument",
            name="financial_backend",
        ),
        migrations.RemoveField(
            model_name="instrument",
            name="isin_lookup",
        ),
        migrations.RemoveField(
            model_name="instrument",
            name="market_data_backend",
        ),
        migrations.RemoveField(
            model_name="instrument",
            name="officer_backend",
        ),
        migrations.RemoveField(
            model_name="instrument",
            name="ric_lookup",
        ),
        migrations.RemoveField(
            model_name="instrument",
            name="statement_backend",
        ),
        migrations.RemoveField(
            model_name="instrument",
            name="ticker_lookup",
        ),
        migrations.RemoveField(
            model_name="instrument",
            name="valoren_lookup",
        ),
        migrations.RemoveField(
            model_name="instrument",
            name="wkn_lookup",
        ),
        migrations.DeleteModel(
            name="InstrumentIdentifier",
        ),
        # Separate from state
        *get_operations(),
    ]
