# Generated by Django 4.2.20 on 2025-04-22 07:50

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('trading', '0001_initial'),
        ('transactions', '0009_alter_transaction_approved_by_and_more'),
        ('users', '0014_alter_crmuser_groups_alter_crmuser_user_permissions_and_more'),
        ('customers', '0013_alter_customerauth_blocked_by_and_more'),
        ('accounts', '0006_alter_account_options'),
        ('system_settings', '0014_alter_paymentgatewayconfig_payment_method_and_more'),
    ]

    operations = [
        migrations.CreateModel(
            name='IBAgreement',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('updated_at', models.DateTimeField(auto_now=True)),
                ('created_by', models.CharField(blank=True, max_length=255, null=True)),
                ('updated_by', models.CharField(blank=True, max_length=255, null=True)),
                ('name', models.CharField(max_length=100)),
                ('description', models.TextField(blank=True)),
                ('is_active', models.BooleanField(default=True)),
            ],
            options={
                'verbose_name': 'IB Agreement',
                'verbose_name_plural': 'IB Agreements',
                'db_table': 'ib_agreements',
            },
        ),
        migrations.CreateModel(
            name='IBViewPermission',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('updated_at', models.DateTimeField(auto_now=True)),
                ('updated_by', models.CharField(blank=True, max_length=255, null=True)),
                ('can_view_full_hierarchy', models.BooleanField(default=False)),
                ('created_by', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='created_ib_permissions', to='users.crmuser')),
                ('customer', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='ib_view_permissions', to='customers.customer')),
            ],
            options={
                'verbose_name': 'IB View Permission',
                'verbose_name_plural': 'IB View Permissions',
                'db_table': 'ib_view_permissions',
            },
        ),
        migrations.CreateModel(
            name='IBCommissionRule',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('updated_at', models.DateTimeField(auto_now=True)),
                ('created_by', models.CharField(blank=True, max_length=255, null=True)),
                ('updated_by', models.CharField(blank=True, max_length=255, null=True)),
                ('commission_type', models.CharField(choices=[('REBATE', 'Rebate'), ('COMMISSION', 'Commission')], help_text='Whether this rule applies to rebates or commissions', max_length=10)),
                ('symbol', models.CharField(blank=True, help_text='NULL means all symbols', max_length=50, null=True)),
                ('calculation_type', models.CharField(choices=[('LOT_BASED', 'Lot Based'), ('PERCENTAGE', 'Percentage'), ('PIP_VALUE', 'Pip Value'), ('TIERED', 'Tiered Volume')], max_length=20)),
                ('value', models.DecimalField(decimal_places=5, help_text='Amount per lot/percentage/pip', max_digits=20)),
                ('keep_percentage', models.DecimalField(decimal_places=2, default=100.0, help_text='Percentage of commission to keep (0-100)', max_digits=5)),
                ('pass_up_percentage', models.DecimalField(decimal_places=2, default=0.0, help_text='Percentage of commission to pass up to parent IB (0-100)', max_digits=5)),
                ('min_amount', models.DecimalField(decimal_places=5, help_text='Minimum commission amount', max_digits=20)),
                ('max_amount', models.DecimalField(decimal_places=5, help_text='Maximum commission amount', max_digits=20)),
                ('min_trade_time', models.IntegerField(default=0, help_text='Minimum trade duration in seconds (anti-scalping)')),
                ('conditions', models.JSONField(blank=True, default=dict, help_text='Additional conditions (volume ranges, etc)')),
                ('priority', models.IntegerField(default=10, help_text='Rule priority (lower number = higher priority)')),
                ('account_type', models.ForeignKey(blank=True, help_text='NULL means all account types', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='commission_rules', to='system_settings.accounttype')),
                ('agreement', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='commission_rules', to='ib_commission.ibagreement')),
            ],
            options={
                'verbose_name': 'IB Commission Rule',
                'verbose_name_plural': 'IB Commission Rules',
                'db_table': 'ib_commission_rules',
            },
        ),
        migrations.CreateModel(
            name='IBAgreementMember',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('updated_at', models.DateTimeField(auto_now=True)),
                ('created_by', models.CharField(blank=True, max_length=255, null=True)),
                ('updated_by', models.CharField(blank=True, max_length=255, null=True)),
                ('is_self_rebate', models.BooleanField(default=False, help_text='Whether the IB can receive rebates from their own trading')),
                ('start_date', models.DateTimeField(blank=True, null=True)),
                ('end_date', models.DateTimeField(blank=True, null=True)),
                ('is_active', models.BooleanField(default=True)),
                ('agreement', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='members', to='ib_commission.ibagreement')),
                ('customer', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='ib_agreements', to='customers.customer')),
            ],
            options={
                'verbose_name': 'IB Agreement Member',
                'verbose_name_plural': 'IB Agreement Members',
                'db_table': 'ib_agreement_members',
            },
        ),
        migrations.CreateModel(
            name='IBAccountAgreement',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('updated_at', models.DateTimeField(auto_now=True)),
                ('created_by', models.CharField(blank=True, max_length=255, null=True)),
                ('updated_by', models.CharField(blank=True, max_length=255, null=True)),
                ('mt5_login', models.IntegerField(help_text='Specific MT5 account login')),
                ('is_self_rebate', models.BooleanField(default=False)),
                ('start_date', models.DateTimeField()),
                ('end_date', models.DateTimeField(blank=True, null=True)),
                ('is_active', models.BooleanField(default=True)),
                ('account', models.ForeignKey(blank=True, help_text='Client account with agreement override', null=True, on_delete=django.db.models.deletion.PROTECT, related_name='ib_agreement_overrides', to='accounts.account')),
                ('agreement', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='account_agreements', to='ib_commission.ibagreement')),
                ('customer', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='account_ib_agreements', to='customers.customer')),
                ('ib_customer', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='ib_account_agreements', to='customers.customer')),
            ],
            options={
                'verbose_name': 'IB Account Agreement',
                'verbose_name_plural': 'IB Account Agreements',
                'db_table': 'ib_account_agreements',
            },
        ),
        migrations.CreateModel(
            name='CommissionTracking',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('updated_at', models.DateTimeField(auto_now=True)),
                ('created_by', models.CharField(blank=True, max_length=255, null=True)),
                ('updated_by', models.CharField(blank=True, max_length=255, null=True)),
                ('commission_type', models.CharField(choices=[('REBATE', 'Rebate'), ('COMMISSION', 'Commission')], max_length=10)),
                ('amount', models.DecimalField(decimal_places=5, max_digits=20)),
                ('processed_time', models.DateTimeField(blank=True, null=True)),
                ('customer', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='commissions_generated', to='customers.customer')),
                ('deal', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='commission_tracking', to='trading.deal')),
                ('direct_ib_customer', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='direct_commissions', to='customers.customer')),
                ('rule', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='commissions', to='ib_commission.ibcommissionrule')),
            ],
            options={
                'verbose_name': 'Commission Tracking',
                'verbose_name_plural': 'Commission Tracking',
                'db_table': 'commission_tracking',
            },
        ),
        migrations.CreateModel(
            name='CommissionDistribution',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('updated_at', models.DateTimeField(auto_now=True)),
                ('created_by', models.CharField(blank=True, max_length=255, null=True)),
                ('updated_by', models.CharField(blank=True, max_length=255, null=True)),
                ('mt5_login', models.IntegerField(help_text="IB's MT5 login")),
                ('amount', models.DecimalField(decimal_places=5, max_digits=20)),
                ('level', models.IntegerField(help_text='IB level in the hierarchy')),
                ('distribution_type', models.CharField(choices=[('REBATE', 'Rebate'), ('COMMISSION', 'Commission')], max_length=10)),
                ('is_pass_up', models.BooleanField(default=False, help_text='Whether this distribution is passed up to parent IB')),
                ('processed_time', models.DateTimeField()),
                ('is_processed', models.BooleanField(default=False, help_text='Whether this distribution has been processed by the financial system')),
                ('processing_status', models.CharField(choices=[('PENDING', 'Pending'), ('PROCESSED', 'Processed'), ('FAILED', 'Failed'), ('CANCELLED', 'Cancelled'), ('DELAYED', 'Delayed - Pending Open Deal'), ('SKIPPED', 'Skipped')], default='PENDING', help_text='Current status of the distribution processing', max_length=20)),
                ('processing_notes', models.TextField(blank=True, help_text='Additional notes about processing status', null=True)),
                ('retry_count', models.IntegerField(default=0, help_text='Number of times processing has been retried for delayed distributions')),
                ('delayed_reason', models.CharField(blank=True, choices=[('MISSING_OPEN_DEAL', 'Missing Opening Deal')], help_text='Reason why processing is delayed', max_length=50, null=True)),
                ('commission_tracking', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='distributions', to='ib_commission.commissiontracking')),
                ('customer', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='commission_distributions', to='customers.customer')),
                ('ib_account', models.ForeignKey(blank=True, help_text="IB's account receiving commissions", null=True, on_delete=django.db.models.deletion.PROTECT, related_name='received_distributions', to='accounts.account')),
                ('rule', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='distributions', to='ib_commission.ibcommissionrule')),
                ('transaction', models.ForeignKey(blank=True, help_text='Associated financial transaction record', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='distributions', to='transactions.commissionrebatetransaction')),
            ],
            options={
                'verbose_name': 'Commission Distribution',
                'verbose_name_plural': 'Commission Distributions',
                'db_table': 'commission_distribution',
            },
        ),
        migrations.CreateModel(
            name='ClientIBMapping',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('updated_at', models.DateTimeField(auto_now=True)),
                ('created_by', models.CharField(blank=True, max_length=255, null=True)),
                ('updated_by', models.CharField(blank=True, max_length=255, null=True)),
                ('ib_path', models.TextField(help_text='Full path of IBs using customer ids')),
                ('mt5_login', models.IntegerField(blank=True, help_text="Client's MT5 login", null=True)),
                ('agreement', models.ForeignKey(blank=True, help_text='Default agreement for this client-IB relationship', null=True, on_delete=django.db.models.deletion.PROTECT, related_name='client_mappings', to='ib_commission.ibagreement')),
                ('customer', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='client_ib_mappings', to='customers.customer')),
                ('direct_ib_customer', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='direct_clients', to='customers.customer')),
                ('master_ib_customer', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='all_hierarchy_clients', to='customers.customer')),
            ],
            options={
                'verbose_name': 'Client IB Mapping',
                'verbose_name_plural': 'Client IB Mappings',
                'db_table': 'client_ib_mapping',
            },
        ),
        migrations.CreateModel(
            name='IBHierarchy',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('updated_at', models.DateTimeField(auto_now=True)),
                ('created_by', models.CharField(blank=True, max_length=255, null=True)),
                ('updated_by', models.CharField(blank=True, max_length=255, null=True)),
                ('level', models.IntegerField(help_text='0 for master IB, increments for each level down')),
                ('path', models.TextField(help_text='Stored as dot-separated customer ids, e.g., "1001.1002.1003"')),
                ('mt5_login', models.IntegerField(help_text='MT5 login for deal processing')),
                ('is_active', models.BooleanField(default=True)),
                ('customer', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='ib_hierarchy', to='customers.customer')),
                ('ib_account', models.ForeignKey(blank=True, help_text='IB account that receives commissions', null=True, on_delete=django.db.models.deletion.PROTECT, related_name='ib_hierarchy_entry', to='accounts.account')),
                ('parent_customer', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='child_ibs', to='customers.customer')),
            ],
            options={
                'verbose_name': 'IB Hierarchy',
                'verbose_name_plural': 'IB Hierarchies',
                'db_table': 'ib_hierarchy',
                'indexes': [models.Index(fields=['mt5_login'], name='ib_hierarch_mt5_log_6732d3_idx'), models.Index(fields=['path'], name='ib_hierarch_path_2dc12e_idx')],
            },
        ),
        migrations.AddConstraint(
            model_name='ibhierarchy',
            constraint=models.UniqueConstraint(fields=('customer',), name='unique_customer_in_hierarchy'),
        ),
        migrations.AddIndex(
            model_name='ibcommissionrule',
            index=models.Index(fields=['agreement', 'priority'], name='ib_commissi_agreeme_27a689_idx'),
        ),
        migrations.AddIndex(
            model_name='ibcommissionrule',
            index=models.Index(fields=['account_type', 'symbol'], name='ib_commissi_account_10d556_idx'),
        ),
        migrations.AddIndex(
            model_name='ibcommissionrule',
            index=models.Index(fields=['commission_type'], name='ib_commissi_commiss_4e605a_idx'),
        ),
        migrations.AddConstraint(
            model_name='ibcommissionrule',
            constraint=models.UniqueConstraint(fields=('agreement', 'commission_type', 'account_type', 'symbol', 'calculation_type'), name='unique_commission_rule_config'),
        ),
        migrations.AddIndex(
            model_name='ibaccountagreement',
            index=models.Index(fields=['mt5_login'], name='ib_account__mt5_log_b8a4b9_idx'),
        ),
        migrations.AddIndex(
            model_name='ibaccountagreement',
            index=models.Index(fields=['customer'], name='ib_account__custome_f687ce_idx'),
        ),
        migrations.AddConstraint(
            model_name='ibaccountagreement',
            constraint=models.UniqueConstraint(fields=('mt5_login', 'ib_customer'), name='unique_account_ib_agreement'),
        ),
        migrations.AddIndex(
            model_name='commissiontracking',
            index=models.Index(fields=['customer'], name='commission__custome_d52e72_idx'),
        ),
        migrations.AddIndex(
            model_name='commissiontracking',
            index=models.Index(fields=['direct_ib_customer'], name='commission__direct__1e1dfb_idx'),
        ),
        migrations.AddIndex(
            model_name='commissiontracking',
            index=models.Index(fields=['rule'], name='commission__rule_id_c3fdd0_idx'),
        ),
        migrations.AddIndex(
            model_name='commissiontracking',
            index=models.Index(fields=['processed_time'], name='commission__process_fc9fe6_idx'),
        ),
        migrations.AddIndex(
            model_name='commissiondistribution',
            index=models.Index(fields=['mt5_login'], name='commission__mt5_log_b7d329_idx'),
        ),
        migrations.AddIndex(
            model_name='commissiondistribution',
            index=models.Index(fields=['customer'], name='commission__custome_fe81ac_idx'),
        ),
        migrations.AddIndex(
            model_name='commissiondistribution',
            index=models.Index(fields=['processed_time'], name='commission__process_f76d89_idx'),
        ),
        migrations.AddIndex(
            model_name='commissiondistribution',
            index=models.Index(fields=['is_processed'], name='commission__is_proc_d409dc_idx'),
        ),
        migrations.AddIndex(
            model_name='commissiondistribution',
            index=models.Index(fields=['processing_status'], name='commission__process_7f8018_idx'),
        ),
        migrations.AddIndex(
            model_name='commissiondistribution',
            index=models.Index(fields=['commission_tracking'], name='commission__commiss_5eb849_idx'),
        ),
        migrations.AddConstraint(
            model_name='commissiondistribution',
            constraint=models.UniqueConstraint(fields=('commission_tracking', 'customer', 'rule', 'is_pass_up'), name='unique_distribution_per_ib_rule_type'),
        ),
        migrations.AddIndex(
            model_name='clientibmapping',
            index=models.Index(fields=['mt5_login'], name='client_ib_m_mt5_log_0c41fe_idx'),
        ),
        migrations.AddIndex(
            model_name='clientibmapping',
            index=models.Index(fields=['customer'], name='client_ib_m_custome_21b923_idx'),
        ),
    ]
