Programming

6. tablw_rwa_view

import io
import pandas as pd
from django.shortcuts import render
from django.http import HttpResponse
# (Import get_rwa_structure from your functions file)

# The 13 Risk Weight Buckets + Total
RWA_COLUMNS = [
    't1_0', 't2_10', 't3_15', 't4_20', 't5_25', 't6_30', 't7_35', 
    't8_50', 't9_75', 't10_100', 't11_125', 't12_150', 't13_200', 'total'
]

def calculate_rwa_metrics():
    """
    Placeholder for your Pandas logic. 
    Returns a dict mapping the code to a dictionary of its column values.
    """
    metrics = {}
    # Example placeholder assignment:
    # metrics['i10000'] = {'t1_0': 150000, 't10_100': 0, 'total': 150000}
    # You will fill this with your dataframe calculations.
    return metrics

def risk_rwa_home(request):
    structure = get_rwa_structure()
    metrics = calculate_rwa_metrics()
    
    # Merge metrics into the structure
    table_data = []
    for item in structure:
        row = item.copy()
        row_metrics = metrics.get(item['code'], {})
        
        # Ensure all 14 columns exist in the row dict (default to 0)
        for col in RWA_COLUMNS:
            row[col] = row_metrics.get(col, 0)
            
        table_data.append(row)

    # Split into 'i' and 'o' for the frontend
    on_balance = [row for row in table_data if row['section'] == 'i']
    off_balance = [row for row in table_data if row['section'] == 'o']

    context = {
        'columns': RWA_COLUMNS,
        'on_balance': on_balance,
        'off_balance': off_balance,
        'report_date': "Placeholder Date" # Pull from session
    }
    return render(request, 'risk/rwa_report.html', context)


def risk_rwa_excel(request):
    structure = get_rwa_structure()
    metrics = calculate_rwa_metrics()
    
    excel_rows = []
    for item in structure:
        row_metrics = metrics.get(item['code'], {})
        row_dict = {
            "Раздел": "Баланс активлари" if item['section'] == 'i' else "Балансдан ташқари",
            "№": item['no'],
            "Кўрсаткичлар": item['name']
        }
        # Add the 13 columns dynamically
        for col in RWA_COLUMNS:
            row_dict[col.replace('t', '').replace('_', '% ')] = row_metrics.get(col, 0)
            
        excel_rows.append(row_dict)

    df = pd.DataFrame(excel_rows)

    buffer = io.BytesIO()
    with pd.ExcelWriter(buffer, engine='xlsxwriter') as writer:
        df.to_excel(writer, sheet_name='RWA_Report', index=False)
        worksheet = writer.sheets['RWA_Report']
        worksheet.set_column('A:A', 20)
        worksheet.set_column('B:B', 8)
        worksheet.set_column('C:C', 60)
        worksheet.set_column('D:Q', 15) # Expand number columns

    buffer.seek(0)
    response = HttpResponse(buffer.read(), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = 'attachment; filename="RWA_Report.xlsx"'
    return response
{% extends 'base.html' %}
{% load humanize %}

{% block content %}
<style>
    body { background-color: #f8f9fa; }
    
    .rwa-container {
        background: white;
        border-radius: 15px;
        padding: 30px;
        box-shadow: 0 5px 25px rgba(0,0,0,0.05);
    }

    /* Table Layout Constraints */
    .table-wrapper {
        max-height: 75vh;
        overflow: auto;
        border-radius: 8px;
        border: 1px solid #dee2e6;
    }
    
    .rwa-table {
        margin-bottom: 0;
        white-space: nowrap;
        font-size: 0.85rem;
    }
    
    .rwa-table th {
        background-color: #1e2b3c !important;
        color: white !important;
        font-weight: 600;
        text-align: center;
        vertical-align: middle;
        position: sticky;
        top: 0;
        z-index: 10;
        border-bottom: 3px solid #e74c3c;
    }
    
    /* Sticky first column so you don't lose the name when scrolling right */
    .sticky-col {
        position: sticky;
        left: 0;
        background-color: white;
        z-index: 5;
        border-right: 2px solid #dee2e6;
        min-width: 400px;
        max-width: 450px;
        white-space: normal; /* Allow text wrap for names */
    }
    .rwa-table th.sticky-col { z-index: 15; background-color: #1e2b3c; }

    /* Hierarchy Indents */
    .level-1 { font-weight: 800; background-color: #f1f5f9; }
    .level-2 { font-weight: 700; padding-left: 2rem !important; }
    .level-3 { padding-left: 3.5rem !important; color: #475569; }

    /* The Blackout Cell Logic */
    .cell-value { font-family: 'Courier New', monospace; font-weight: 700; text-align: right; }
    .cell-black { 
        background-color: #111827 !important; 
        color: #111827 !important; /* Hide the '0' entirely */
        border: 1px solid #1f2937;
    }
    .cell-black:hover { background-color: #1f2937 !important; } /* Slight hover effect */

    .section-divider {
        background-color: #e74c3c !important;
        color: white !important;
        text-transform: uppercase;
        font-weight: 800;
        letter-spacing: 2px;
        text-align: center;
        padding: 15px !important;
    }
</style>

<div class="container-fluid py-4">
    <div class="rwa-container">
        
        <!-- Header & Controls -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h2 class="fw-bold m-0"><i class="fas fa-shield-halved text-danger me-2"></i> Таваккалчиликка тортилган активлар (RWA)</h2>
                <p class="text-muted mb-0 mt-1">Отчетная дата: <span class="fw-bold text-dark">{{ report_date }}</span></p>
            </div>
            <div>
                <a href="{% url 'risk-rwa-excel' %}" class="btn btn-outline-success fw-bold rounded-pill px-4 shadow-sm">
                    <i class="fas fa-file-excel me-2"></i> Скачать Excel
                </a>
            </div>
        </div>

        <div class="table-wrapper">
            <table class="table table-bordered table-hover rwa-table">
                <thead>
                    <tr>
                        <th style="width: 50px;">№</th>
                        <th class="sticky-col">Кўрсаткичлар</th>
                        
                        <!-- 13 Risk Columns -->
                        <th>0%</th>
                        <th>10%</th>
                        <th>15%</th>
                        <th>20%</th>
                        <th>25%</th>
                        <th>30%</th>
                        <th>35%</th>
                        <th>50%</th>
                        <th>75%</th>
                        <th>100%</th>
                        <th>125%</th>
                        <th>150%</th>
                        <th>200%</th>
                        
                        <!-- Total -->
                        <th style="background-color: #2c3e50 !important; border-left: 2px solid white;">ЖАМИ</th>
                    </tr>
                </thead>
                <tbody>
                    
                    <!-- SECTION 1: ON-BALANCE -->
                    <tr>
                        <td colspan="16" class="section-divider">Баланс активлари</td>
                    </tr>
                    
                    {% for row in on_balance %}
                    <tr class="{% if row.is_header %}level-1{% endif %}">
                        <td class="text-center text-muted fw-bold">{{ row.no }}</td>
                        <td class="sticky-col level-{{ row.level }}">{{ row.name }}</td>
                        
                        <!-- Dynamically render the 13 columns + total -->
                        {% for col in columns %}
                            <!-- Lookup the value. If 0, apply cell-black class -->
                            {% for key, val in row.items %}
                                {% if key == col %}
                                    <td class="cell-value {% if val == 0 %}cell-black{% endif %}" 
                                        {% if col == 'total' %}style="background-color: #f8f9fa; border-left: 2px solid #dee2e6;"{% endif %}>
                                        {% if val != 0 %}{{ val|floatformat:0|intcomma }}{% endif %}
                                    </td>
                                {% endif %}
                            {% endfor %}
                        {% endfor %}
                    </tr>
                    {% endfor %}

                    <!-- SECTION 2: OFF-BALANCE -->
                    <tr>
                        <td colspan="16" class="section-divider" style="background-color: #2980b9 !important;">Балансдан ташқари активлар</td>
                    </tr>

                    {% for row in off_balance %}
                    <tr class="{% if row.is_header %}level-1{% endif %}">
                        <td class="text-center text-muted fw-bold">{{ row.no }}</td>
                        <td class="sticky-col level-{{ row.level }}">{{ row.name }}</td>
                        
                        {% for col in columns %}
                            {% for key, val in row.items %}
                                {% if key == col %}
                                    <td class="cell-value {% if val == 0 %}cell-black{% endif %}"
                                        {% if col == 'total' %}style="background-color: #f8f9fa; border-left: 2px solid #dee2e6;"{% endif %}>
                                        {% if val != 0 %}{{ val|floatformat:0|intcomma }}{% endif %}
                                    </td>
                                {% endif %}
                            {% endfor %}
                        {% endfor %}
                    </tr>
                    {% endfor %}

                </tbody>
            </table>
        </div>
    </div>
</div>
{% endblock %}
Foydali bo'ldimi? Yoqmadi 0 Baholash uchun kiring