# Generated by Django 5.2.19 on 2026-12-02 03:02

import django.db.models.deletion
import uuid
from decimal import Decimal
from django.conf import settings
from django.db import migrations, models


def backfill_treasury_upgrades(apps, schema_editor):
    BankGuarantee = apps.get_model("loans", "BankGuarantee")
    LoanCollateral = apps.get_model("loans", "LoanCollateral")
    FacilityCollateralLink = apps.get_model("loans", "FacilityCollateralLink")

    for bg in BankGuarantee.objects.all():
        updated = False
        if not bg.original_expiry_date and bg.expiry_date:
            bg.original_expiry_date = bg.expiry_date
            updated = True
        if (not bg.original_amount or bg.original_amount == Decimal("0.00")) and bg.amount:
            bg.original_amount = bg.amount
            updated = True
        if not bg.effective_date and bg.issue_date:
            bg.effective_date = bg.issue_date
            updated = True
        if updated:
            bg.save(update_fields=["original_expiry_date", "original_amount", "effective_date"])

    for col in LoanCollateral.objects.filter(facility__isnull=False):
        if not FacilityCollateralLink.objects.filter(collateral=col, facility=col.facility).exists():
            FacilityCollateralLink.objects.create(
                company=col.company,
                collateral=col,
                facility=col.facility,
                allocated_value=col.assessed_value,
                charge_ref=col.lien_mortgage_ref,
                is_released=col.is_released,
                released_at=col.released_at,
            )


class Migration(migrations.Migration):

    dependencies = [
        ('accounting', '0010_voucherregisterviewconfig_and_more'),
        ('banking', '0005_bankaccount_account_owner_name_and_more'),
        ('loans', '0002_bankfacility_accrued_interest_account_and_more'),
        ('projects', '0002_dailysitereport_projectactivity_projectadvance_and_more'),
        ('tenancy', '0003_taxconfig_calculation_rule_taxconfig_category_and_more'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.AddField(
            model_name='bankfacility',
            name='bank_charges_account',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='charge_facilities', to='accounting.account'),
        ),
        migrations.AddField(
            model_name='bankfacility',
            name='charge_interest_on_credit',
            field=models.BooleanField(default=False),
        ),
        migrations.AddField(
            model_name='bankfacility',
            name='current_portion_liability_account',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='current_loan_facilities', to='accounting.account'),
        ),
        migrations.AddField(
            model_name='bankfacility',
            name='fx_gain_account',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='fx_gain_facilities', to='accounting.account'),
        ),
        migrations.AddField(
            model_name='bankfacility',
            name='fx_loss_account',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='fx_loss_facilities', to='accounting.account'),
        ),
        migrations.AddField(
            model_name='bankfacility',
            name='interest_frequency',
            field=models.CharField(choices=[('DAILY', 'Daily Accrual'), ('MONTHLY', 'Monthly'), ('QUARTERLY', 'Quarterly'), ('HALF_YEARLY', 'Half-Yearly'), ('ANNUAL', 'Annual'), ('BULLET', 'Bullet at Maturity'), ('CUSTOM', 'Custom Contractual')], default='MONTHLY', max_length=16),
        ),
        migrations.AddField(
            model_name='bankfacility',
            name='interest_start_date',
            field=models.DateField(blank=True, null=True),
        ),
        migrations.AddField(
            model_name='bankfacility',
            name='monthly_contract_rate',
            field=models.DecimalField(blank=True, decimal_places=4, max_digits=6, null=True),
        ),
        migrations.AddField(
            model_name='bankfacility',
            name='penal_interest_account',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='penal_facilities', to='accounting.account'),
        ),
        migrations.AddField(
            model_name='bankfacility',
            name='processing_fee_account',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='fee_facilities', to='accounting.account'),
        ),
        migrations.AddField(
            model_name='bankfacility',
            name='repayment_start_date',
            field=models.DateField(blank=True, null=True),
        ),
        migrations.AddField(
            model_name='bankguarantee',
            name='actual_release_date',
            field=models.DateField(blank=True, null=True),
        ),
        migrations.AddField(
            model_name='bankguarantee',
            name='application_date',
            field=models.DateField(blank=True, null=True),
        ),
        migrations.AddField(
            model_name='bankguarantee',
            name='approval_date',
            field=models.DateField(blank=True, null=True),
        ),
        migrations.AddField(
            model_name='bankguarantee',
            name='bank_branch',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='guarantees', to='banking.bankbranch'),
        ),
        migrations.AddField(
            model_name='bankguarantee',
            name='bank_charges',
            field=models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18),
        ),
        migrations.AddField(
            model_name='bankguarantee',
            name='beneficiary_address',
            field=models.CharField(blank=True, max_length=255),
        ),
        migrations.AddField(
            model_name='bankguarantee',
            name='beneficiary_contact',
            field=models.CharField(blank=True, max_length=120),
        ),
        migrations.AddField(
            model_name='bankguarantee',
            name='beneficiary_org_type',
            field=models.CharField(blank=True, max_length=64),
        ),
        migrations.AddField(
            model_name='bankguarantee',
            name='beneficiary_pan',
            field=models.CharField(blank=True, max_length=64),
        ),
        migrations.AddField(
            model_name='bankguarantee',
            name='commission_basis',
            field=models.CharField(default='PER_ANNUM', max_length=32),
        ),
        migrations.AddField(
            model_name='bankguarantee',
            name='commission_rate',
            field=models.DecimalField(decimal_places=4, default=Decimal('0.0000'), max_digits=6),
        ),
        migrations.AddField(
            model_name='bankguarantee',
            name='contract_number',
            field=models.CharField(blank=True, max_length=80),
        ),
        migrations.AddField(
            model_name='bankguarantee',
            name='contract_value',
            field=models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18),
        ),
        migrations.AddField(
            model_name='bankguarantee',
            name='effective_date',
            field=models.DateField(blank=True, null=True),
        ),
        migrations.AddField(
            model_name='bankguarantee',
            name='expected_release_date',
            field=models.DateField(blank=True, null=True),
        ),
        migrations.AddField(
            model_name='bankguarantee',
            name='internal_ref',
            field=models.CharField(blank=True, max_length=64),
        ),
        migrations.AddField(
            model_name='bankguarantee',
            name='margin_release_voucher',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='bg_margin_releases', to='accounting.voucher'),
        ),
        migrations.AddField(
            model_name='bankguarantee',
            name='original_amount',
            field=models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18),
        ),
        migrations.AddField(
            model_name='bankguarantee',
            name='original_expiry_date',
            field=models.DateField(blank=True, null=True),
        ),
        migrations.AddField(
            model_name='bankguarantee',
            name='purpose',
            field=models.CharField(blank=True, max_length=255),
        ),
        migrations.AddField(
            model_name='bankguarantee',
            name='revocation_date',
            field=models.DateField(blank=True, null=True),
        ),
        migrations.AddField(
            model_name='bankguarantee',
            name='tender_number',
            field=models.CharField(blank=True, max_length=80),
        ),
        migrations.AddField(
            model_name='drawingpowerassessment',
            name='creditor_deductions',
            field=models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18),
        ),
        migrations.AddField(
            model_name='drawingpowerassessment',
            name='eligible_raw_materials',
            field=models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18),
        ),
        migrations.AddField(
            model_name='drawingpowerassessment',
            name='eligible_wip',
            field=models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18),
        ),
        migrations.AddField(
            model_name='drawingpowerassessment',
            name='notes',
            field=models.CharField(blank=True, max_length=255),
        ),
        migrations.AddField(
            model_name='drawingpowerassessment',
            name='other_deductions',
            field=models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18),
        ),
        migrations.AddField(
            model_name='loancollateral',
            name='collateral_code',
            field=models.CharField(blank=True, max_length=48),
        ),
        migrations.AddField(
            model_name='loancollateral',
            name='encumbrance_date',
            field=models.DateField(blank=True, null=True),
        ),
        migrations.AddField(
            model_name='loancollateral',
            name='forced_sale_value',
            field=models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18),
        ),
        migrations.AddField(
            model_name='loancollateral',
            name='haircut_pct',
            field=models.DecimalField(decimal_places=2, default=Decimal('25.00'), max_digits=5),
        ),
        migrations.AddField(
            model_name='loancollateral',
            name='lifecycle_status',
            field=models.CharField(choices=[('PROPOSED', 'Proposed'), ('SUBMITTED', 'Submitted'), ('VALUED', 'Valued'), ('BANK_ACCEPTED', 'Bank Accepted'), ('CHARGED', 'Charged / Encumbered'), ('ACTIVE', 'Active'), ('RELEASE_REQUESTED', 'Release Requested'), ('BANK_DISCHARGED', 'Bank Discharged'), ('RELEASED', 'Released')], default='ACTIVE', max_length=24),
        ),
        migrations.AddField(
            model_name='loancollateral',
            name='location',
            field=models.CharField(blank=True, max_length=255),
        ),
        migrations.AddField(
            model_name='loancollateral',
            name='market_value',
            field=models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18),
        ),
        migrations.AddField(
            model_name='loancollateral',
            name='next_valuation_date',
            field=models.DateField(blank=True, null=True),
        ),
        migrations.AddField(
            model_name='loancollateral',
            name='owner_type',
            field=models.CharField(default='COMPANY', max_length=48),
        ),
        migrations.AddField(
            model_name='loancollateral',
            name='project',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='collaterals', to='projects.project'),
        ),
        migrations.AddField(
            model_name='loancollateral',
            name='registration_no',
            field=models.CharField(blank=True, max_length=120),
        ),
        migrations.AddField(
            model_name='loanscheduleinstallment',
            name='fees_due',
            field=models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18),
        ),
        migrations.AddField(
            model_name='loanscheduleinstallment',
            name='fees_paid',
            field=models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18),
        ),
        migrations.AddField(
            model_name='loanscheduleinstallment',
            name='is_postponed',
            field=models.BooleanField(default=False),
        ),
        migrations.AddField(
            model_name='loanscheduleinstallment',
            name='penal_paid',
            field=models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18),
        ),
        migrations.AddField(
            model_name='loanscheduleinstallment',
            name='postponement_reason',
            field=models.CharField(blank=True, max_length=255),
        ),
        migrations.AlterField(
            model_name='bankfacility',
            name='day_count_basis',
            field=models.CharField(choices=[('ACT_365', 'Actual / 365'), ('ACT_360', 'Actual / 360'), ('ACT_ACT', 'Actual / Actual'), ('30_360', '30 / 360'), ('FIXED_30', 'Fixed 30-Day Month'), ('CALENDAR_MONTH', 'Actual Calendar Month'), ('CONTRACT_MONTHLY', 'Contract-Specific Monthly Rate')], default='ACT_365', max_length=20),
        ),
        migrations.AlterField(
            model_name='bankfacility',
            name='interest_mode',
            field=models.CharField(choices=[('FIXED', 'Fixed Rate'), ('FLOATING', 'Floating (Base Rate + Premium)'), ('CUSTOM', 'Custom Effective-Dated Schedule')], default='FLOATING', max_length=12),
        ),
        migrations.AlterField(
            model_name='bankfacility',
            name='repayment_frequency',
            field=models.CharField(choices=[('DAILY', 'Daily Accrual'), ('MONTHLY', 'Monthly'), ('QUARTERLY', 'Quarterly'), ('HALF_YEARLY', 'Half-Yearly'), ('ANNUAL', 'Annual'), ('BULLET', 'Bullet at Maturity'), ('CUSTOM', 'Custom Contractual')], default='MONTHLY', max_length=16),
        ),
        migrations.AlterField(
            model_name='bankfacility',
            name='schedule_method',
            field=models.CharField(choices=[('EMI', 'Equal Monthly/Periodic Installment (EMI)'), ('EQUAL_PRINCIPAL', 'Equal Principal + Reducing Interest'), ('REDUCING_BALANCE', 'Reducing Balance'), ('BULLET', 'Bullet Repayment'), ('INTEREST_ONLY', 'Interest Only + Principal at Maturity'), ('BALLOON', 'Balloon Repayment'), ('CUSTOM_PRINCIPAL', 'Custom Principal Schedule'), ('IRREGULAR', 'Irregular Installments')], default='EMI', max_length=20),
        ),
        migrations.AlterField(
            model_name='bankguarantee',
            name='bg_type',
            field=models.CharField(choices=[('BID_BOND', 'Bid Bond / Tender Guarantee'), ('PERFORMANCE', 'Performance Guarantee'), ('ADVANCE_PAYMENT', 'Advance Payment Guarantee'), ('MOBILIZATION_ADVANCE', 'Mobilization Advance Guarantee'), ('RETENTION_MONEY', 'Retention Money Guarantee'), ('FINANCIAL', 'Financial Guarantee'), ('CUSTOMS', 'Customs Guarantee'), ('PAYMENT', 'Payment Guarantee'), ('CONTRACTUAL', 'Contractual Guarantee'), ('OTHER', 'Other Guarantee')], max_length=24),
        ),
        migrations.AlterField(
            model_name='bankguarantee',
            name='status',
            field=models.CharField(choices=[('DRAFT', 'Draft'), ('APPLIED', 'Application Submitted'), ('INTERNAL_APPROVED', 'Internal Approved'), ('BANK_PROCESSING', 'Bank Processing'), ('ISSUED', 'Issued'), ('ACTIVE', 'Active (Contingent Exposure)'), ('AMENDED', 'Amended'), ('EXTENDED', 'Extended'), ('EXPIRED_AWAITING_RELEASE', 'Expired Awaiting Release'), ('RELEASE_REQUESTED', 'Release Requested'), ('RELEASE_CONFIRMED', 'Release Confirmed'), ('RELEASED', 'Released & Closed'), ('CLAIMED', 'Claim Received'), ('PARTIALLY_INVOKED', 'Partially Invoked'), ('INVOKED', 'Fully Invoked (Funded Liability)'), ('REVOKED', 'Revoked / Cancelled')], default='ACTIVE', max_length=28),
        ),
        migrations.AlterField(
            model_name='loancollateral',
            name='company',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='collaterals', to='tenancy.company'),
        ),
        migrations.AlterField(
            model_name='loancollateral',
            name='facility',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='collaterals', to='loans.bankfacility'),
        ),
        migrations.AlterField(
            model_name='loancollateral',
            name='security_type',
            field=models.CharField(choices=[('LAND_BUILDING', 'Land & Building'), ('EQUIPMENT_VEHICLE', 'Equipment & Vehicles'), ('FIXED_DEPOSIT', 'Fixed Deposit Lien'), ('CASH_MARGIN', 'Cash Margin Deposit'), ('INVENTORY_RECEIVABLES', 'Inventory & Receivables'), ('SHARES_SECURITIES', 'Shares & Securities'), ('PERSONAL_GUARANTEE', 'Personal Guarantee'), ('CORPORATE_GUARANTEE', 'Corporate Guarantee'), ('OTHER', 'Other Contractual Security')], max_length=28),
        ),
        migrations.AlterField(
            model_name='loaninterestaccrual',
            name='day_count_basis',
            field=models.CharField(default='ACT_365', max_length=20),
        ),
        migrations.CreateModel(
            name='CollateralRelease',
            fields=[
                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ('release_date', models.DateField()),
                ('discharge_ref', models.CharField(max_length=120)),
                ('is_partial', models.BooleanField(default=False)),
                ('notes', models.TextField(blank=True)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('approved_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)),
                ('collateral', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='release_records', to='loans.loancollateral')),
                ('company', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='tenancy.company')),
            ],
        ),
        migrations.CreateModel(
            name='CollateralValuation',
            fields=[
                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ('valuation_date', models.DateField()),
                ('valuer_name', models.CharField(max_length=150)),
                ('valuation_report_no', models.CharField(blank=True, max_length=80)),
                ('market_value', models.DecimalField(decimal_places=2, max_digits=18)),
                ('forced_sale_value', models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18)),
                ('haircut_pct', models.DecimalField(decimal_places=2, default=Decimal('25.00'), max_digits=5)),
                ('eligible_security_value', models.DecimalField(decimal_places=2, max_digits=18)),
                ('next_valuation_date', models.DateField(blank=True, null=True)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('approved_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)),
                ('collateral', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='valuations', to='loans.loancollateral')),
                ('company', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='tenancy.company')),
            ],
            options={
                'ordering': ['-valuation_date', '-created_at'],
            },
        ),
        migrations.CreateModel(
            name='DrawingPowerConfig',
            fields=[
                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ('stock_margin_pct', models.DecimalField(decimal_places=2, default=Decimal('25.00'), max_digits=5)),
                ('raw_material_margin_pct', models.DecimalField(decimal_places=2, default=Decimal('25.00'), max_digits=5)),
                ('allow_wip', models.BooleanField(default=False)),
                ('wip_margin_pct', models.DecimalField(decimal_places=2, default=Decimal('50.00'), max_digits=5)),
                ('receivable_margin_pct', models.DecimalField(decimal_places=2, default=Decimal('30.00'), max_digits=5)),
                ('debtor_aging_limit_days', models.PositiveSmallIntegerField(default=90)),
                ('drawing_power_cap', models.DecimalField(blank=True, decimal_places=2, max_digits=18, null=True)),
                ('submission_frequency', models.CharField(default='MONTHLY', max_length=16)),
                ('next_stock_statement_due', models.DateField(blank=True, null=True)),
                ('next_debtor_statement_due', models.DateField(blank=True, null=True)),
                ('excluded_collateral_notes', models.CharField(blank=True, max_length=255)),
                ('updated_at', models.DateTimeField(auto_now=True)),
                ('facility', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='dp_config', to='loans.bankfacility')),
            ],
        ),
        migrations.CreateModel(
            name='FacilityCollateralLink',
            fields=[
                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ('allocated_value', models.DecimalField(decimal_places=2, max_digits=18)),
                ('charge_rank', models.CharField(default='FIRST_PARI_PASSU', max_length=32)),
                ('charge_ref', models.CharField(blank=True, max_length=120)),
                ('is_released', models.BooleanField(default=False)),
                ('released_at', models.DateField(blank=True, null=True)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('collateral', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='allocations', to='loans.loancollateral')),
                ('company', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='tenancy.company')),
                ('facility', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='collateral_links', to='loans.bankfacility')),
                ('guarantee', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='collateral_links', to='loans.bankguarantee')),
            ],
        ),
        migrations.CreateModel(
            name='GuaranteeAmendment',
            fields=[
                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ('version_no', models.PositiveSmallIntegerField(default=1)),
                ('amendment_date', models.DateField()),
                ('amendment_type', models.CharField(max_length=32)),
                ('previous_amount', models.DecimalField(decimal_places=2, max_digits=18)),
                ('new_amount', models.DecimalField(decimal_places=2, max_digits=18)),
                ('previous_beneficiary', models.CharField(blank=True, max_length=200)),
                ('new_beneficiary', models.CharField(blank=True, max_length=200)),
                ('amendment_charges', models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18)),
                ('reason', models.CharField(max_length=255)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('approved_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)),
                ('charge_voucher', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='accounting.voucher')),
                ('company', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='tenancy.company')),
                ('guarantee', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='amendments', to='loans.bankguarantee')),
            ],
            options={
                'ordering': ['-version_no', '-created_at'],
            },
        ),
        migrations.CreateModel(
            name='GuaranteeClaim',
            fields=[
                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ('claim_notice_date', models.DateField()),
                ('claiming_beneficiary', models.CharField(max_length=200)),
                ('claimed_amount', models.DecimalField(decimal_places=2, max_digits=18)),
                ('accepted_amount', models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18)),
                ('recovery_amount', models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18)),
                ('dispute_status', models.CharField(choices=[('RECEIVED', 'Notice Received'), ('UNDER_REVIEW', 'Under Assessment'), ('DISPUTED', 'Disputed'), ('ACCEPTED_PARTIAL', 'Partially Accepted'), ('ACCEPTED_FULL', 'Fully Invoked & Settled')], default='RECEIVED', max_length=24)),
                ('claim_reason', models.TextField(blank=True)),
                ('bank_response', models.TextField(blank=True)),
                ('settlement_date', models.DateField(blank=True, null=True)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('company', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='tenancy.company')),
                ('created_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)),
                ('guarantee', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='claims', to='loans.bankguarantee')),
                ('voucher', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='accounting.voucher')),
            ],
        ),
        migrations.CreateModel(
            name='GuaranteeDocument',
            fields=[
                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ('doc_category', models.CharField(default='ORIGINAL_BG', max_length=40)),
                ('version_no', models.PositiveSmallIntegerField(default=1)),
                ('title', models.CharField(max_length=200)),
                ('document_ref', models.CharField(blank=True, max_length=120)),
                ('file_name', models.CharField(blank=True, max_length=255)),
                ('uploaded_at', models.DateTimeField(auto_now_add=True)),
                ('company', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='tenancy.company')),
                ('guarantee', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='documents', to='loans.bankguarantee')),
                ('uploaded_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'ordering': ['-uploaded_at'],
            },
        ),
        migrations.CreateModel(
            name='GuaranteeExtension',
            fields=[
                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ('previous_expiry_date', models.DateField()),
                ('new_expiry_date', models.DateField()),
                ('previous_claim_expiry_date', models.DateField(blank=True, null=True)),
                ('new_claim_expiry_date', models.DateField(blank=True, null=True)),
                ('extension_charges', models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18)),
                ('bank_advice_ref', models.CharField(blank=True, max_length=120)),
                ('reason', models.CharField(max_length=255)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('approved_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)),
                ('charge_voucher', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='accounting.voucher')),
                ('company', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='tenancy.company')),
                ('guarantee', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='extensions', to='loans.bankguarantee')),
            ],
            options={
                'ordering': ['-created_at'],
            },
        ),
        migrations.CreateModel(
            name='GuaranteeRelease',
            fields=[
                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ('release_type', models.CharField(default='FORMAL_RELEASE', max_length=32)),
                ('beneficiary_discharge_ref', models.CharField(max_length=120)),
                ('bank_release_confirmation_ref', models.CharField(max_length=120)),
                ('release_date', models.DateField()),
                ('margin_refunded_amount', models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18)),
                ('notes', models.TextField(blank=True)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('approved_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)),
                ('company', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='tenancy.company')),
                ('guarantee', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='release_record', to='loans.bankguarantee')),
                ('margin_release_voucher', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='accounting.voucher')),
            ],
        ),
        migrations.CreateModel(
            name='InterestCalculationRun',
            fields=[
                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ('period_start', models.DateField()),
                ('period_end', models.DateField()),
                ('day_count_basis', models.CharField(default='ACT_365', max_length=20)),
                ('opening_balance', models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18)),
                ('normal_interest', models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18)),
                ('penal_interest', models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18)),
                ('fee_amount', models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18)),
                ('total_calculated', models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18)),
                ('bank_charged_interest', models.DecimalField(blank=True, decimal_places=2, max_digits=18, null=True)),
                ('difference_amount', models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18)),
                ('status', models.CharField(choices=[('DRAFT', 'Draft'), ('SUBMITTED', 'Submitted for Approval'), ('APPROVED', 'Approved'), ('POSTED', 'Posted to GL')], default='DRAFT', max_length=16)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('approved_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='+', to=settings.AUTH_USER_MODEL)),
                ('company', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='tenancy.company')),
                ('created_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='+', to=settings.AUTH_USER_MODEL)),
                ('facility', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='calculation_runs', to='loans.bankfacility')),
                ('voucher', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='accounting.voucher')),
            ],
            options={
                'ordering': ['-period_end', '-created_at'],
            },
        ),
        migrations.CreateModel(
            name='InterestDailyDetail',
            fields=[
                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ('calc_date', models.DateField()),
                ('opening_balance', models.DecimalField(decimal_places=2, max_digits=18)),
                ('drawdown', models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18)),
                ('repayment', models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18)),
                ('closing_debit_balance', models.DecimalField(decimal_places=2, max_digits=18)),
                ('applicable_rate', models.DecimalField(decimal_places=4, max_digits=7)),
                ('rate_version_code', models.CharField(blank=True, max_length=24)),
                ('daily_interest', models.DecimalField(decimal_places=4, max_digits=18)),
                ('penal_interest', models.DecimalField(decimal_places=4, default=Decimal('0.0000'), max_digits=18)),
                ('is_excess_limit', models.BooleanField(default=False)),
                ('run', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='daily_details', to='loans.interestcalculationrun')),
            ],
            options={
                'ordering': ['calc_date'],
            },
        ),
        migrations.CreateModel(
            name='ODCreditTransaction',
            fields=[
                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ('txn_date', models.DateField(db_index=True)),
                ('value_date', models.DateField(db_index=True)),
                ('txn_type', models.CharField(choices=[('DRAWDOWN', 'Drawdown'), ('DEPOSIT', 'Deposit / Recovery'), ('TRANSFER', 'Transfer'), ('INTEREST_DEBIT', 'Interest Debit'), ('BANK_CHARGE', 'Bank Charge'), ('EXCESS_TEMP', 'Temporary Enhancement / Excess'), ('LIMIT_CHANGE', 'Limit Reduction / Renewal')], max_length=20)),
                ('debit_amount', models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18)),
                ('credit_amount', models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=18)),
                ('reference_no', models.CharField(blank=True, max_length=80)),
                ('narration', models.CharField(blank=True, max_length=255)),
                ('is_cleared', models.BooleanField(default=True)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('company', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='tenancy.company')),
                ('created_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)),
                ('facility', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='od_transactions', to='loans.bankfacility')),
                ('voucher', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='accounting.voucher')),
            ],
            options={
                'ordering': ['value_date', 'created_at'],
            },
        ),
        migrations.CreateModel(
            name='FacilityRateVersion',
            fields=[
                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ('version_code', models.CharField(max_length=24)),
                ('rate_kind', models.CharField(choices=[('NORMAL', 'Normal Interest'), ('PENAL', 'Penal Interest'), ('OVERDUE', 'Overdue Default Rate')], default='NORMAL', max_length=16)),
                ('rate_type', models.CharField(choices=[('FIXED', 'Fixed Rate'), ('FLOATING', 'Floating (Base Rate + Premium)'), ('CUSTOM', 'Custom Effective-Dated Schedule')], default='FLOATING', max_length=12)),
                ('rate_unit', models.CharField(choices=[('ANNUAL', 'Annual Rate (% p.a.)'), ('MONTHLY', 'Contractual Monthly Rate (% p.m.)'), ('DAILY', 'Daily Rate (%)')], default='ANNUAL', max_length=12)),
                ('benchmark_name', models.CharField(blank=True, max_length=80)),
                ('benchmark_value', models.DecimalField(decimal_places=4, default=Decimal('0.0000'), max_digits=6)),
                ('spread_pct', models.DecimalField(decimal_places=4, default=Decimal('0.0000'), max_digits=6)),
                ('effective_rate_pct', models.DecimalField(decimal_places=4, max_digits=7)),
                ('penal_rate_pct', models.DecimalField(decimal_places=4, default=Decimal('2.0000'), max_digits=6)),
                ('effective_from', models.DateField(db_index=True)),
                ('effective_to', models.DateField(blank=True, null=True)),
                ('next_reset_date', models.DateField(blank=True, null=True)),
                ('status', models.CharField(choices=[('SCHEDULED', 'Scheduled'), ('CURRENT', 'Current'), ('SUPERSEDED', 'Superseded')], default='CURRENT', max_length=16)),
                ('approval_ref', models.CharField(blank=True, max_length=80)),
                ('reason', models.CharField(blank=True, max_length=255)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('approved_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='+', to=settings.AUTH_USER_MODEL)),
                ('company', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='tenancy.company')),
                ('created_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='+', to=settings.AUTH_USER_MODEL)),
                ('facility', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rate_versions', to='loans.bankfacility')),
            ],
            options={
                'ordering': ['effective_from', 'created_at'],
                'unique_together': {('facility', 'version_code')},
            },
        ),
        migrations.RunPython(backfill_treasury_upgrades, migrations.RunPython.noop),
    ]
