/**
* Executive BI Dashboard Engine v4.0 - Master Edition
* Iranian Ecommerce & Brand Ecosystem Benchmark (1385-1404)
* Standard: Stripe / Linear Executive BI (Pure Light Theme, RTL Vazirmatn)
*/
function getBundle() {
if (typeof window !== 'undefined' && window.bundle) return window.bundle;
if (typeof globalThis !== 'undefined' && globalThis.bundle) return globalThis.bundle;
return {};
}
function parsePersianFloat(str) {
if (str === null || str === undefined) return 0;
const clean = String(str).replace(/[٪%]/g, '').trim();
const english = clean.replace(/[۰-۹]/g, d => '۰۱۲۳۴۵۶۷۸۹'.indexOf(d));
const val = parseFloat(english);
return isNaN(val) ? 0 : val;
}
function toPersianDigits(num) {
if (num === null || num === undefined) return '';
return String(num).replace(/[0-9]/g, d => '۰۱۲۳۴۵۶۷۸۹'[d]);
}
function formatNumber(num) {
if (num === null || num === undefined || isNaN(num)) return '۰';
return Number(num).toLocaleString('fa-IR');
}
function safeStr(val) {
if (val === null || val === undefined) return '';
return String(val);
}
function safeCreateIcons() {
try {
if (typeof lucide !== 'undefined' && typeof lucide.createIcons === 'function') {
lucide.createIcons();
}
} catch (e) {
console.warn("Lucide icon generation skipped:", e);
}
}
// -------------------------------------------------------------
// 1. BRAND MARKET INTELLIGENCE & LOST OPPORTUNITY (FLAGSHIP)
// -------------------------------------------------------------
function renderBrandMarketIntelligence() {
try {
const bData = getBundle().brand_market_intelligence || {};
const categories = bData.categories || [];
const lostAnalysis = bData.lost_brand_market_analysis || {};
const domesticPipeline = bData.top_domestic_brands_pipeline || [];
// 1.1 Master Reference Table
const tbody = document.getElementById('brand-market-table-tbody');
if (tbody) {
tbody.innerHTML = categories.map(cat => {
const cit = (cat.citations && cat.citations.length > 0) ? cat.citations[0] : null;
return `
|
${safeStr(cat.name_fa)}
${safeStr(cat.name_en)}
|
${formatNumber(cat.total_size_irr)} همت
$${cat.total_size_usd}B
|
${cat.official_pct}٪
${formatNumber(cat.official_irr)} همت
|
${cat.unofficial_pct}٪
${formatNumber(cat.unofficial_irr)} همت
|
${cat.domestic_share_pct}٪ بومی
/
${cat.foreign_share_pct}٪ خارجی
|
بومی: ${(cat.top_domestic_brands || []).slice(0, 3).join(', ')}
خارجی: ${(cat.top_foreign_brands || []).slice(0, 3).join(', ')}
|
${safeStr(cat.regulatory_drivers)}
|
${cit ? `
سند مصاحبه
` : '—'}
|
`;
}).join('');
}
// 1.2 Category Profile Cards
const catContainer = document.getElementById('brand-market-categories-cards');
if (catContainer) {
catContainer.innerHTML = categories.map(cat => `
${safeStr(cat.name_fa)}
${safeStr(cat.name_en)}
ارزش کل: ${formatNumber(cat.total_size_irr)} همت ($${cat.total_size_usd}B)
سهم رسمی: ${cat.official_pct}٪ (${formatNumber(cat.official_irr)} همت)
سهم غیررسمی/قاچاق: ${cat.unofficial_pct}٪ (${formatNumber(cat.unofficial_irr)} همت)
برندهای لیدر بومی (${cat.domestic_share_pct}٪):
${(cat.top_domestic_brands || []).map(b => `${b}`).join('')}
برندهای رقیب خارجی (${cat.foreign_share_pct}٪):
${(cat.top_foreign_brands || []).map(b => `${b}`).join('')}
روشها و کریدورهای ورود قاچاق:
${safeStr(cat.smuggling_vectors)}
سیاستهای حاکمیتی و محرکهای رگولاتوری:
${safeStr(cat.regulatory_drivers)}
${(cat.citations && cat.citations.length > 0) ? `
اسناد استنادی و مصاحبهها:
${cat.citations.map(cit => `
${safeStr(cit.speaker_entity)}
"${safeStr(cit.key_quote)}"
مشاهده سند
`).join('')}
` : ''}
`).join('');
}
// 1.3 Smuggling Corridors
const corContainer = document.getElementById('brand-market-corridors-cards');
if (corContainer) {
const corridors = bData.macro_corridors || [];
corContainer.innerHTML = corridors.map(c => `
${safeStr(c.corridor_name)}
مبادی: ${safeStr(c.origin)}
مقاصد دپو: ${safeStr(c.target)}
اقلام غالب:
${safeStr(c.dominant_categories)}
${safeStr(c.mechanism)}
`).join('');
}
// 1.4 Lost Brand Opportunity Strategy Cards
const lostCardsBox = document.getElementById('lost-opportunity-cards-container');
if (lostCardsBox && lostAnalysis.lost_opportunity_breakdown) {
lostCardsBox.innerHTML = lostAnalysis.lost_opportunity_breakdown.map(ch => `
${safeStr(ch.channel)}
پتانسیل جذب: ${ch.addressable_potential_irr} همت
اندازه کل کانال: ${ch.channel_scale_irr} همت
استراتژی آزادسازی: ${safeStr(ch.capture_strategy)}
`).join('');
}
// 1.5 Top Domestic Brands Financial Pipeline Table
const domTbody = document.getElementById('top-domestic-brands-tbody');
if (domTbody && domesticPipeline.length > 0) {
domTbody.innerHTML = domesticPipeline.map(item => `
|
${safeStr(item.brand_name)}
${safeStr(item.key_products)}
|
${safeStr(item.industry)} |
${formatNumber(item.total_annual_sales_irr)} همت
|
${formatNumber(item.current_digikala_sales_irr)} همت
|
${item.current_share_pct}٪
|
${formatNumber(item.addressable_digikala_potential_irr)} همت
|
${safeStr(item.growth_multiple)}
|
${safeStr(item.unlocking_mechanism)}
|
`).join('');
}
console.log("✓ renderBrandMarketIntelligence completed");
} catch (e) {
console.error("Error in renderBrandMarketIntelligence:", e);
}
}
// -------------------------------------------------------------
// 2. WAR CRISIS 1404
// -------------------------------------------------------------
function renderWarTable() {
try {
const tbody = document.getElementById('war-table-tbody');
if (!tbody) return;
const war = getBundle().war_report_1404 || {};
const shifts = war.commodities_shift || [];
tbody.innerHTML = shifts.map(item => {
const changeRaw = safeStr(item.change_pct);
const isPostWar = changeRaw.includes('پساجنگ');
const pureChange = changeRaw.replace('(پساجنگ)', '').trim();
return `
|
${safeStr(item.category)}
|
${pureChange}
${isPostWar ? `` : ''}
|
${safeStr(item.behavior)} |
${safeStr(item.strategy)} |
${safeStr(item.supply_status)}
|
`;
}).join('');
console.log("✓ renderWarTable completed with clean styling");
} catch (e) {
console.error("Error in renderWarTable:", e);
}
}
// -------------------------------------------------------------
// 3. COMMISSIONS & CONTRACTS (8-COLUMN COMPLETE TABLE)
// -------------------------------------------------------------
function renderContractsTable() {
try {
const tbody = document.getElementById('contracts-table-tbody');
if (!tbody) return;
const contracts = getBundle().commissions_data || [];
tbody.innerHTML = contracts.map(item => {
const avgNum = item.avg_commission !== undefined ? toPersianDigits(item.avg_commission) + '٪' : safeStr(item.average_commission_pct);
const rawDays = safeStr(item.payment_cycle_days || item.settlement_days_standard);
const isFast = rawDays.includes('تسویه سریع');
const cleanDays = rawDays.replace('(تسویه سریع)', '').trim();
return `
|
${safeStr(item.category_fa || item.category_name)}
${safeStr(item.category_en)}
|
${safeStr(item.commission_range)}
|
${avgNum}
|
${cleanDays}
${isFast ? `` : ''}
|
${safeStr(item.fbd_processing_fee)}
|
${safeStr(item.return_rate_est || item.return_rate_estimate)}
|
${safeStr(item.rules_and_conditions || item.sla_penalty_and_terms)}
|
سند
|
`;
}).join('');
console.log("✓ renderContractsTable completed with clean borderless typography");
} catch (e) {
console.error("Error in renderContractsTable:", e);
}
}
// -------------------------------------------------------------
// 4. BRAND ECOSYSTEM PILLARS (RICH SUB-SERVICES RENDERING)
// -------------------------------------------------------------
function renderBrandEcosystem() {
try {
const container = document.getElementById('ecosystem-pillars-container');
if (!container) return;
const data = getBundle().brand_ecosystem_pillars || [];
container.innerHTML = data.map((p, idx) => {
const pillarNum = toPersianDigits(String(idx + 1).padStart(2, '0'));
const pillarId = `PILLAR-${String(idx + 1).padStart(2, '0')}`;
const rawName = p.pillar_name_fa || p.title || 'رکن اکوسیستم';
let nameFa = rawName;
let nameEn = '';
if (rawName.includes('(') && rawName.includes(')')) {
const parts = rawName.split('(');
nameFa = parts[0].trim();
nameEn = parts[1].replace(')', '').trim();
}
const desc = p.description || '';
const services = p.services || [];
return `
${pillarNum}
${safeStr(nameFa)}
${nameEn ? `
${safeStr(nameEn)}
` : ''}
${safeStr(pillarId)}
${safeStr(desc)}
زیرسیستمها و ابزارهای خلق ارزش برای برندها (${toPersianDigits(services.length)} سرویس فعال):
${services.map(s => `
${safeStr(s.service_name)}
سال ${safeStr(s.year_introduced)}
${safeStr(s.mechanism)}
ارزش برای برند: ${safeStr(s.value_for_brand)}
ارزش برای کاربر: ${safeStr(s.value_for_user)}
${s.brands_using ? `
برندهای شاخص فعال:
${safeStr(s.brands_using)}
` : ''}
`).join('')}
`;
}).join('');
console.log("✓ renderBrandEcosystem completed with clean titles");
} catch (e) {
console.error("Error in renderBrandEcosystem:", e);
}
}
// -------------------------------------------------------------
// 5. GROWTH LEVERS (12 LEVERS)
// -------------------------------------------------------------
function renderGrowthLevers() {
try {
const container = document.getElementById('growth-levers-container');
if (!container) return;
const data = getBundle().growth_levers_data || [];
container.innerHTML = data.map(lever => {
const id = lever.id || 'GL';
const name = lever.name || lever.lever_title || 'اهرم رشد';
const category = lever.category || lever.pillar_category || 'عمومی';
const period = lever.period_active || '';
const mechanism = lever.mechanism || lever.operational_mechanism || '';
const impact = lever.impact_data || lever.quantified_impact || '';
const sourceTitle = lever.source_title || 'مشاهده سند ارجاعی';
const sourceUrl = lever.source_url || lever.source_link || '';
return `
${safeStr(category)}
${period ? `${safeStr(period)}` : ''}
${safeStr(id)}
${safeStr(name)}
${safeStr(mechanism)}
`;
}).join('');
console.log("✓ renderGrowthLevers completed with 12 full cards");
} catch (e) {
console.error("Error in renderGrowthLevers:", e);
}
}
// -------------------------------------------------------------
// 6. REVENUE MODELS & 3-SIDED ANALYSIS
// -------------------------------------------------------------
function renderRevenueModels() {
try {
const roadmapBox = document.getElementById('revenue-roadmap-container');
const fullCardsBox = document.getElementById('revenue-models-full-cards');
const data = getBundle().revenue_models_data || [];
if (roadmapBox) {
roadmapBox.innerHTML = data.map(m => `
${safeStr(m.name)}
${safeStr(m.mechanism)}
${safeStr(m.share_of_revenue_1403)}
`).join('');
}
if (fullCardsBox) {
fullCardsBox.innerHTML = data.map(m => `
${safeStr(m.name)}
سال معرفی: ${safeStr(m.year_introduced)}
سهم از درآمد کل (۱۴۰۳):
${safeStr(m.share_of_revenue_1403)}
${safeStr(m.mechanism)}
خریدار نهایی (User Impact):
${safeStr(m.user_side_impact)}
فروشنده و برند (Brand Impact):
${safeStr(m.brand_side_impact)}
رگولاتور و دولت (Gov & Tax):
${safeStr(m.gov_tax_aspect)}
${m.source_url ? `
` : ''}
`).join('');
}
console.log("✓ renderRevenueModels completed with 3-sided analysis");
} catch (e) {
console.error("Error in renderRevenueModels:", e);
}
}
// -------------------------------------------------------------
// 7. 20-YEAR TIMELINE (FULL 20-YEAR METRICS & 4-BOX ARCHITECTURE)
// -------------------------------------------------------------
function renderTimelineCards(filterYear = 'all') {
try {
const container = document.getElementById('timeline-cards-list');
if (!container) return;
const timeline = getBundle().yearly_metrics || [];
const filtered = (filterYear === 'all') ? timeline : timeline.filter(y => y.year_shamsi === filterYear);
container.innerHTML = filtered.map(item => `
${safeStr(item.year_shamsi)}
${safeStr(item.year_gregorian)}
${safeStr(item.phase)}
نفوذ ایکامرس در ایران: ${item.ecom_penetration_iran || '۰.۰۵'}٪
${item.domestic_brand_share}٪ بومی
${item.foreign_brand_share}٪ خارجی
تنوع کالا (SKU):
${formatNumber(item.sku_count)}
فروشندگان فعال:
${formatNumber(item.active_sellers)}
سفارش روزانه:
${formatNumber(item.daily_orders)}
نیروی انسانی:
${formatNumber(item.workforce)} نفر
${(item.top_brands && item.top_brands.length > 0) ? `
برندهای لیدر سال:
${item.top_brands.map(b => `${b}`).join('')}
` : ''}
دستاوردها و اتفاقات کلیدی:
${(item.milestones || []).map(m => `- ${safeStr(m)}
`).join('')}
پیوتها و شکستهای مسیر:
${(item.pivots_and_failures || []).map(p => `- ${safeStr(p)}
`).join('')}
تحولات ساختار مدیریتی:
${(item.management_shifts || []).map(ms => `- ${safeStr(ms)}
`).join('')}
شرایط کلان اقتصادی و رگولاتوری:
${(item.regulatory_and_macro || []).map(r => `- ${safeStr(r)}
`).join('')}
`).join('');
console.log("✓ renderTimelineCards completed for 20 years");
} catch (e) {
console.error("Error in renderTimelineCards:", e);
}
}
function filterTimeline() {
const sel = document.getElementById('timeline-filter-select');
if (!sel) return;
renderTimelineCards(sel.value);
}
// -------------------------------------------------------------
// 8. EXECUTIVES DIRECTORY (COMPLETE VIDEO TITLES & CLEAN BIDI)
// -------------------------------------------------------------
function renderExecutivesCards() {
try {
const container = document.getElementById('executives-cards-container');
if (!container) return;
const data = getBundle().executives_directory || [];
container.innerHTML = data.map(exec => {
const interviews = exec.interview_videos || exec.key_interviews || exec.direct_interviews || [];
return `
${safeStr(exec.role_category)}
${safeStr(exec.tenure)}
${safeStr(exec.name).slice(0, 2)}
${safeStr(exec.name)}
${safeStr(exec.title)}
دیدگاه استراتژیک در قبال برندها:
${safeStr(exec.stance_on_brands || exec.key_stance)}
${interviews.length > 0 ? `
مصاحبهها و ویدیوهای فکتچکشده:
` : ''}
`;
}).join('');
console.log("✓ renderExecutivesCards completed");
} catch (e) {
console.error("Error in renderExecutivesCards:", e);
}
}
// -------------------------------------------------------------
// 9. PLAYBOOK & CANNIBALIZATION (100% FILLED, ZERO DASHES)
// -------------------------------------------------------------
function renderPlaybookSections() {
try {
const pDossier = getBundle().playbook_dossier || {};
// 1. Brands
const brandsBox = document.getElementById('playbook-brands-container');
if (brandsBox && pDossier.how_digikala_convinced_brands) {
brandsBox.innerHTML = pDossier.how_digikala_convinced_brands.map((item, idx) => `
${safeStr(item.pillar || item.tactic || `${idx+1}. راهکار سازمانی`)}
${safeStr(item.description || item.mechanism)}
${item.quantified_impact ? `
دستاورد: ${safeStr(item.quantified_impact)}
` : ''}
`).join('');
}
// 2. Users
const usersBox = document.getElementById('playbook-users-container');
if (usersBox && pDossier.how_digikala_convinced_users) {
usersBox.innerHTML = pDossier.how_digikala_convinced_users.map((item, idx) => `
${safeStr(item.pillar || item.tactic || `${idx+1}. سیاست اعتمادسازی`)}
${safeStr(item.description || item.mechanism)}
${(item.quantified_retention || item.result) ? `
اثر اعتماد: ${safeStr(item.quantified_retention || item.result)}
` : ''}
`).join('');
}
// 3. Cannibalization
const cannibalBox = document.getElementById('playbook-cannibal-container');
if (cannibalBox && pDossier.how_digikala_resolved_cannibalization) {
cannibalBox.innerHTML = pDossier.how_digikala_resolved_cannibalization.map(item => `
${safeStr(item.entity || item.vertical_conflict)}
راهکار ساختاری
صورت مسئله و تعارض: ${safeStr(item.problem)}
راهکار تثبیتشده: ${safeStr(item.solution || item.structural_solution)}
`).join('');
}
console.log("✓ renderPlaybookSections completed with full text");
} catch (e) {
console.error("Error in renderPlaybookSections:", e);
}
}
// -------------------------------------------------------------
// 10. POSTMORTEMS GRID (PIVOT-01 TO 06 & TYPO FIXES)
// -------------------------------------------------------------
function renderPostmortemsGrid() {
try {
const container = document.getElementById('postmortems-grid-container');
if (!container) return;
const data = getBundle().failures_and_pivots_dossier || [];
container.innerHTML = data.map(item => {
const fallout = item.consequences_and_fallout || item.consequences || '';
const pivotId = item.id || 'PIVOT';
return `
${safeStr(item.title)}
${safeStr(pivotId)}
سال ${safeStr(item.year)}
علت ریشهای:
${safeStr(item.root_cause)}
نحوه اجرا، تبعات و خسارات اولیه:
${safeStr(fallout)}
راهکار نهایی تثبیتشده و پیوت موفق:
${safeStr(item.resolution)}
`;
}).join('');
console.log("✓ renderPostmortemsGrid completed");
} catch (e) {
console.error("Error in renderPostmortemsGrid:", e);
}
}
// -------------------------------------------------------------
// 11. MARKET & CHANNELS (WITH 8TH COLUMN: VERIFIED SOURCES)
// -------------------------------------------------------------
// -------------------------------------------------------------
// 10.1 REGULATORY RESTRICTIONS MASTER MATRIX
// -------------------------------------------------------------
function renderRegulatoryMatrix() {
try {
const tbody = document.getElementById('regulatory-matrix-tbody');
if (!tbody) return;
const matrix = getBundle().regulatory_restrictions_matrix || [];
tbody.innerHTML = matrix.map(item => {
let feasBadge = '';
if (item.supply_feasibility_type === 'yes') {
feasBadge = '✓ ' + safeStr(item.supply_feasibility) + '';
} else if (item.supply_feasibility_type === 'conditional') {
feasBadge = '⚠ ' + safeStr(item.supply_feasibility) + '';
} else {
feasBadge = '✕ ' + safeStr(item.supply_feasibility) + '';
}
let riskBadge = 'bg-slate-100 text-slate-700 border-slate-200';
if (item.regulatory_risk_level && (item.regulatory_risk_level.includes('بحرانی') || item.regulatory_risk_level.includes('امنیتی'))) {
riskBadge = 'bg-rose-50 text-rose-800 border-rose-200 font-extrabold';
} else if (item.regulatory_risk_level && item.regulatory_risk_level.includes('بسیار بالا')) {
riskBadge = 'bg-amber-50 text-amber-800 border-amber-200 font-bold';
} else if (item.regulatory_risk_level && item.regulatory_risk_level.includes('بالا')) {
riskBadge = 'bg-blue-50 text-blue-800 border-blue-200 font-medium';
}
const rawChannels = safeStr(item.supply_channels_active);
const channels = rawChannels.split(String.fromCharCode(10));
return `
|
${safeStr(item.category)}
${safeStr(item.category_en)}
|
${safeStr(item.latest_status_1403_1404)}
|
${feasBadge}
|
${channels.map(ch => ` ${ch} `).join('')}
|
${safeStr(item.online_sales_status)}
|
${safeStr(item.key_regulator)}
${safeStr(item.regulatory_risk_level)}
|
|
`;
}).join('');
console.log("✓ renderRegulatoryMatrix completed with strict table-fixed alignment");
} catch (e) {
console.error("Error in renderRegulatoryMatrix:", e);
}
}
// -------------------------------------------------------------
// 10.2 FOUNDER WAR STORIES & REGULATORY TRAUMAS (10 CARDS)
// -------------------------------------------------------------
function renderFounderWarStories() {
try {
const container = document.getElementById('founder-war-stories-container');
if (!container) return;
const stories = getBundle().founder_war_stories || [];
container.innerHTML = stories.map(st => `
${safeStr(st.founder).slice(0, 2)}
${safeStr(st.founder)}
${safeStr(st.platform)} (${safeStr(st.role)})
${safeStr(st.id)}
${safeStr(st.period)}
رخداد و شوک رگولاتوری/بازار:
${safeStr(st.incident_title)}
${safeStr(st.narrative)}
استراتژی سازگاری و نحوه حل مسئله:
${safeStr(st.adaptation_strategy)}
درسآموخته استراتژیک (Strategic Takeaway):
${safeStr(st.strategic_lesson)}
${st.source_url ? `
` : ''}
`).join('');
console.log("✓ renderFounderWarStories completed");
} catch (e) {
console.error("Error in renderFounderWarStories:", e);
}
}
function renderMarketTable() {
try {
const tbody = document.getElementById('market-table-tbody');
if (!tbody) return;
const data = getBundle().market_channel_breakdown || [];
tbody.innerHTML = data.map(item => `
| ${safeStr(item.sector)} |
${formatNumber(item.total_market_size_irr_thousand_b)} همت |
${item.ecommerce_official_share}٪
|
${item.social_commerce_share}٪
|
${item.traditional_offline_share}٪ |
${item.smuggling_rate}٪
|
${safeStr(item.key_drivers)} |
${item.source_url ? `
${safeStr(item.source_type || 'سند و متدولوژی')}
` : '—'}
|
`).join('');
console.log("✓ renderMarketTable completed with sources");
} catch (e) {
console.error("Error in renderMarketTable:", e);
}
}
// -------------------------------------------------------------
// 12. CATEGORIES MATRIX (TOP SEARCHED QUERIES & SANA FIX)
// -------------------------------------------------------------
function renderCategoriesFull() {
try {
const container = document.getElementById('categories-full-container');
if (!container) return;
const data = getBundle().category_brand_deep_matrix || [];
container.innerHTML = data.map(cat => {
const irBrands = Array.isArray(cat.top_iranian_brands) ? cat.top_iranian_brands : [];
const frBrands = Array.isArray(cat.top_foreign_brands) ? cat.top_foreign_brands : [];
const searchQueries = Array.isArray(cat.top_searched_queries) ? cat.top_searched_queries : [];
return `
${safeStr(cat.category_name)}
نسبت داخلی به خارجی: ${safeStr(cat.foreign_vs_domestic_ratio)}
•
سهم از GMV کل: ${cat.share_of_total_gmv_1403}٪
برندهای لیدر بومی و ایرانی:
${irBrands.map(b => `${b}`).join('')}
برندهای رقیب خارجی (رسمی و خاکستری):
${frBrands.map(b => `${b}`).join('')}
${searchQueries.length > 0 ? `
پرسرجترین کلمات کلیدی و برندهای این رده در پلتفرم:
${searchQueries.map(q => `${q}`).join('')}
` : ''}
موانع و گلوگاههای رگولاتوری: ${safeStr(cat.key_regulatory_barrier)}
دینامیک و تحولات بازار: ${safeStr(cat.dynamics_and_shifts)}
`;
}).join('');
console.log("✓ renderCategoriesFull completed with search queries");
} catch (e) {
console.error("Error in renderCategoriesFull:", e);
}
}
// -------------------------------------------------------------
// 13. SOURCES VAULT (PAGE SIZE, PROPER YEARS, FAST FILTER)
// -------------------------------------------------------------
let currentVaultPage = 1;
const vaultPageSize = 25;
let filteredSources = [];
function searchVault(page = 1) {
try {
const queryEl = document.getElementById('vault-search-box');
const platformEl = document.getElementById('vault-filter-platform');
const q = queryEl ? queryEl.value.trim().toLowerCase() : '';
const p = platformEl ? platformEl.value : 'all';
const sources = window.allSources || [];
filteredSources = sources.filter(s => {
const matchesP = (p === 'all') || (s.platform === p);
if (!matchesP) return false;
if (!q) return true;
return (
(s.title && s.title.toLowerCase().includes(q)) ||
(s.category && s.category.toLowerCase().includes(q)) ||
(s.summary && s.summary.toLowerCase().includes(q)) ||
(s.entities && s.entities.toLowerCase().includes(q))
);
});
currentVaultPage = page;
const totalPages = Math.ceil(filteredSources.length / vaultPageSize) || 1;
if (currentVaultPage > totalPages) currentVaultPage = totalPages;
if (currentVaultPage < 1) currentVaultPage = 1;
const startIdx = (currentVaultPage - 1) * vaultPageSize;
const pageItems = filteredSources.slice(startIdx, startIdx + vaultPageSize);
const tbody = document.getElementById('vault-table-rows');
if (tbody) {
tbody.innerHTML = pageItems.map(item => `
| ${safeStr(item.id)} |
${safeStr(item.title)}
|
${safeStr(item.platform)}
|
${safeStr(item.category)} |
${safeStr(item.publication_year || item.year || '۱۳۹۵-۱۴۰۴')} |
${item.url ? `
مشاهده
` : '—'}
|
`).join('');
}
const counterEl = document.getElementById('vault-rows-counter');
if (counterEl) {
counterEl.innerText = `نمایش ${startIdx + 1} تا ${Math.min(startIdx + vaultPageSize, filteredSources.length)} از مجموع ${formatNumber(filteredSources.length)} منبع معتبر`;
}
const pageInfoEl = document.getElementById('vault-page-info');
if (pageInfoEl) {
pageInfoEl.innerText = `صفحه ${currentVaultPage} از ${totalPages}`;
}
const btnPrev = document.getElementById('vault-btn-prev');
const btnNext = document.getElementById('vault-btn-next');
if (btnPrev) btnPrev.disabled = (currentVaultPage <= 1);
if (btnNext) btnNext.disabled = (currentVaultPage >= totalPages);
safeCreateIcons();
} catch (e) {
console.error("Error in searchVault:", e);
}
}
function nextVaultPage() {
searchVault(currentVaultPage + 1);
}
function prevVaultPage() {
searchVault(currentVaultPage - 1);
}
// -------------------------------------------------------------
// 14. PLOTLY CHARTS (8 CHARTS TOTAL INCLUDING LOST BRAND MARKET)
// -------------------------------------------------------------
function initPlotlyCharts() {
if (typeof Plotly === 'undefined') {
console.warn("Plotly not available. Chart initialization skipped.");
return;
}
// GLOBAL IDEMPOTENT GUARD: heavy renderers (the 20-year timeline in particular)
// can bubble an error up the call stack; without this guard the whole chart
// block was skipped silently. Now every chart is attempted independently.
function chartRoot(id) { return document.getElementById(id); }
function draw(id) {
var el = chartRoot(id);
if (!el) { console.warn("Chart container missing in DOM: " + id); return null; }
if (typeof Plotly.purge === 'function') { try { Plotly.purge(el); } catch (e) { } }
return el;
}
const defaultFont = { family: 'Vazirmatn, sans-serif', size: 11, color: '#0F172A' };
// Chart 1: Timeline Growth
try {
const timeline = getBundle().yearly_metrics || [];
const years = timeline.map(t => t.year_shamsi);
const skus = timeline.map(t => t.sku_count);
const sellers = timeline.map(t => t.active_sellers);
const traceSku = {
x: years,
y: skus,
name: 'تنوع کالا (SKU)',
type: 'scatter',
mode: 'lines+markers',
line: { shape: 'spline', smoothing: 1.3, color: '#4F46E5', width: 3 },
marker: { size: 6, color: '#4F46E5' },
fill: 'tozeroy',
fillcolor: 'rgba(79, 70, 229, 0.04)',
yaxis: 'y1'
};
const traceSellers = {
x: years,
y: sellers,
name: 'فروشندگان فعال',
type: 'scatter',
mode: 'lines+markers',
line: { shape: 'spline', smoothing: 1.3, color: '#059669', width: 2.5, dash: 'solid' },
marker: { size: 5, color: '#059669' },
yaxis: 'y2'
};
const layoutGrowth = {
font: defaultFont,
paper_bgcolor: '#FFFFFF',
plot_bgcolor: '#FFFFFF',
margin: { l: 60, r: 60, t: 30, b: 40 },
legend: { orientation: 'h', y: 1.15, x: 0.5, xanchor: 'center' },
xaxis: { gridcolor: '#F1F5F9', zeroline: false },
yaxis: { title: 'تنوع کالا (SKU - مقیاس لگاریتمی)', type: 'log', gridcolor: '#F1F5F9', zeroline: false },
yaxis2: { title: 'فروشندگان فعال', type: 'log', overlaying: 'y', side: 'right', gridcolor: 'transparent', zeroline: false }
};
if (draw('plotly-timeline-growth')) Plotly.newPlot('plotly-timeline-growth', [traceSku, traceSellers], layoutGrowth, { responsive: true, displayModeBar: false });
} catch (e) {
console.error("Error rendering plotly-timeline-growth:", e);
}
// Chart 2: Brands Stacked
try {
const timeline = getBundle().yearly_metrics || [];
const years = timeline.map(t => t.year_shamsi);
const domestic = timeline.map(t => t.domestic_brand_share);
const foreign = timeline.map(t => t.foreign_brand_share);
const traceDom = {
x: years,
y: domestic,
name: 'سهم برندهای ایرانی (بومی)',
type: 'bar',
marker: { color: '#10B981' }
};
const traceFor = {
x: years,
y: foreign,
name: 'سهم برندهای خارجی',
type: 'bar',
marker: { color: '#F43F5E' }
};
const layoutBrands = {
barmode: 'stack',
font: defaultFont,
paper_bgcolor: '#FFFFFF',
plot_bgcolor: '#FFFFFF',
margin: { l: 50, r: 20, t: 30, b: 40 },
legend: { orientation: 'h', y: 1.15, x: 0.5, xanchor: 'center' },
xaxis: { gridcolor: '#F1F5F9', zeroline: false },
yaxis: { title: 'درصد سهم از سبد کالا', range: [0, 100], gridcolor: '#F1F5F9', zeroline: false }
};
if (draw('plotly-brands-stacked')) Plotly.newPlot('plotly-brands-stacked', [traceDom, traceFor], layoutBrands, { responsive: true, displayModeBar: false });
} catch (e) {
console.error("Error rendering plotly-brands-stacked:", e);
}
// Chart 3: Quadrant Scatter
try {
const market = getBundle().market_channel_breakdown || [];
const xOnline = market.map(m => m.ecommerce_official_share);
const ySmuggle = market.map(m => m.smuggling_rate);
const labels = market.map(m => m.sector);
const traceScatter = {
x: xOnline,
y: ySmuggle,
text: labels,
mode: 'markers+text',
textposition: 'top center',
textfont: { size: 10, color: '#0F172A', family: 'Vazirmatn', weight: 'bold' },
marker: {
size: [32, 28, 42, 26, 24, 22],
color: ['#4F46E5', '#06B6D4', '#10B981', '#F59E0B', '#EC4899', '#8B5CF6'],
opacity: 0.9,
line: { width: 1.5, color: '#0F172A' }
},
type: 'scatter'
};
const layoutScatter = {
font: defaultFont,
paper_bgcolor: '#FFFFFF',
plot_bgcolor: '#FFFFFF',
margin: { l: 50, r: 30, t: 30, b: 50 },
xaxis: { title: 'نرخ نفوذ خردهفروشی آنلاین (٪)', gridcolor: '#F1F5F9', zeroline: false, range: [0, 35] },
yaxis: { title: 'نرخ تخمینی قاچاق و خاکستری (٪)', gridcolor: '#F1F5F9', zeroline: false, range: [0, 55] },
shapes: [
{ type: 'line', x0: 15, x1: 15, y0: 0, y1: 55, line: { dash: 'dash', color: '#CBD5E1', width: 1.5 } },
{ type: 'line', x0: 0, x1: 35, y0: 25, y1: 25, line: { dash: 'dash', color: '#CBD5E1', width: 1.5 } }
],
annotations: [
{ x: 30, y: 50, text: 'قاچاق بالا / آنلاین بالا', showarrow: false, font: { size: 9, color: '#94A3B8' } },
{ x: 5, y: 50, text: 'قاچاق بالا / آنلاین پایین', showarrow: false, font: { size: 9, color: '#94A3B8' } },
{ x: 30, y: 5, text: 'قاچاق پایین / آنلاین بالا', showarrow: false, font: { size: 9, color: '#94A3B8' } },
{ x: 5, y: 5, text: 'قاچاق پایین / آنلاین پایین', showarrow: false, font: { size: 9, color: '#94A3B8' } }
]
};
if (draw('plotly-quadrant-scatter')) Plotly.newPlot('plotly-quadrant-scatter', [traceScatter], layoutScatter, { responsive: true, displayModeBar: false });
} catch (e) {
console.error("Error rendering plotly-quadrant-scatter:", e);
}
// Chart 4: Market Channels Grouped Bar
try {
const market = getBundle().market_channel_breakdown || [];
const sectors = market.map(m => m.sector.split(' ')[0]);
const ecom = market.map(m => m.ecommerce_official_share);
const social = market.map(m => m.social_commerce_share);
const offline = market.map(m => m.traditional_offline_share);
const tEcom = { x: sectors, y: ecom, name: 'ایکامرس رسمی', type: 'bar', marker: { color: '#4F46E5' } };
const tSocial = { x: sectors, y: social, name: 'سوشال / اینستاگرام', type: 'bar', marker: { color: '#E11D48' } };
const tOffline = { x: sectors, y: offline, name: 'بازار سنتی فیزیکی', type: 'bar', marker: { color: '#94A3B8' } };
const layoutChannels = {
barmode: 'group',
font: defaultFont,
paper_bgcolor: '#FFFFFF',
plot_bgcolor: '#FFFFFF',
margin: { l: 50, r: 20, t: 30, b: 40 },
legend: { orientation: 'h', y: 1.15, x: 0.5, xanchor: 'center' },
xaxis: { gridcolor: '#F1F5F9', zeroline: false },
yaxis: { title: 'درصد سهم کانال', range: [0, 100], gridcolor: '#F1F5F9', zeroline: false }
};
if (draw('plotly-market-channels')) Plotly.newPlot('plotly-market-channels', [tEcom, tSocial, tOffline], layoutChannels, { responsive: true, displayModeBar: false });
} catch (e) {
console.error("Error rendering plotly-market-channels:", e);
}
// Chart 5: Revenue Models Donut (PROPORTIONAL REAL DATA)
try {
const revs = getBundle().revenue_models_data || [];
const labels = revs.map(r => r.name.split('(')[0].trim());
const values = revs.map(r => parsePersianFloat(r.share_of_revenue_1403));
const traceDonut = {
labels: labels,
values: values,
type: 'pie',
hole: 0.62,
marker: {
colors: ['#4F46E5', '#10B981', '#06B6D4', '#F59E0B', '#EC4899', '#8B5CF6', '#64748B']
},
textinfo: 'percent',
textposition: 'inside',
textfont: { family: 'Vazirmatn', size: 11, color: '#FFFFFF', weight: 'bold' },
insidetextorientation: 'horizontal',
hoverinfo: 'label+percent+value'
};
const layoutDonut = {
font: defaultFont,
paper_bgcolor: '#FFFFFF',
plot_bgcolor: '#FFFFFF',
margin: { l: 20, r: 20, t: 20, b: 60 },
showlegend: true,
legend: {
orientation: 'h',
y: -0.12,
x: 0.5,
xanchor: 'center',
font: { size: 10, family: 'Vazirmatn' }
},
annotations: [
{
font: { size: 13, family: 'Vazirmatn', weight: 'bold', color: '#0F172A' },
showarrow: false,
text: 'ترکیب سهم
درآمد ۱۴۰۳',
x: 0.5,
y: 0.5
}
]
};
if (draw('plotly-revenue-donut')) Plotly.newPlot('plotly-revenue-donut', [traceDonut], layoutDonut, { responsive: true, displayModeBar: false });
} catch (e) {
console.error("Error rendering plotly-revenue-donut:", e);
}
// Chart 6: Brand Market Split (Stacked Horizontal Bar)
try {
const bData = getBundle().brand_market_intelligence || {};
const bCats = bData.categories || [];
const catNames = bCats.map(c => (c.name_fa || '').split('،')[0].trim());
const officialVals = bCats.map(c => c.official_pct || 0);
const unofficialVals = bCats.map(c => c.unofficial_pct || 0);
const officialIrr = bCats.map(c => c.official_irr || 0);
const unofficialIrr = bCats.map(c => c.unofficial_irr || 0);
const traceOfficial = {
y: catNames,
x: officialVals,
name: 'سهم کانال رسمی (تولید + واردات قانونی)',
type: 'bar',
orientation: 'h',
marker: { color: '#10B981' },
text: officialVals.map((v, i) => `${v}٪ (${officialIrr[i]} همت)`),
textposition: 'inside',
insidetextanchor: 'middle',
textfont: { color: '#FFFFFF', family: 'Vazirmatn', size: 10, weight: 'bold' }
};
const traceUnofficial = {
y: catNames,
x: unofficialVals,
name: 'سهم غیررسمی (قاچاق + خاکستری)',
type: 'bar',
orientation: 'h',
marker: { color: '#F43F5E' },
text: unofficialVals.map((v, i) => `${v}٪ (${unofficialIrr[i]} همت)`),
textposition: 'inside',
insidetextanchor: 'middle',
textfont: { color: '#FFFFFF', family: 'Vazirmatn', size: 10, weight: 'bold' }
};
const layoutSplit = {
barmode: 'stack',
font: defaultFont,
paper_bgcolor: '#FFFFFF',
plot_bgcolor: '#FFFFFF',
margin: { l: 120, r: 20, t: 30, b: 40 },
legend: { orientation: 'h', y: 1.15, x: 0.5, xanchor: 'center' },
xaxis: { title: 'درصد سهم از بازار', range: [0, 100], gridcolor: '#F1F5F9', zeroline: false },
yaxis: { autorange: 'reversed', gridcolor: '#F1F5F9', zeroline: false }
};
if (draw('plotly-brand-market-split')) Plotly.newPlot('plotly-brand-market-split', [traceOfficial, traceUnofficial], layoutSplit, { responsive: true, displayModeBar: false });
} catch (e) {
console.error("Error rendering plotly-brand-market-split:", e);
}
// Chart 7: Brand Market Bubble
try {
const bData = getBundle().brand_market_intelligence || {};
const bCats = bData.categories || [];
const catNames = bCats.map(c => (c.name_fa || '').split('،')[0].trim());
const xDomestic = bCats.map(c => c.domestic_share_pct || 0);
const yUnofficial = bCats.map(c => c.unofficial_pct || 0);
const totalIrr = bCats.map(c => c.total_size_irr || 50);
const bubbleSizes = totalIrr.map(v => Math.max(24, Math.sqrt(v) * 2.8));
const traceBubble = {
x: xDomestic,
y: yUnofficial,
text: catNames.map((n, i) => `${n}
${totalIrr[i]} همت`),
mode: 'markers+text',
textposition: 'top center',
textfont: { size: 10, color: '#0F172A', family: 'Vazirmatn', weight: 'bold' },
marker: {
size: bubbleSizes,
color: ['#3B82F6', '#10B981', '#EC4899', '#8B5CF6', '#F59E0B', '#06B6D4', '#6366F1', '#14B8A6'],
opacity: 0.85,
line: { width: 1.5, color: '#0F172A' }
},
type: 'scatter'
};
const layoutBubble = {
font: defaultFont,
paper_bgcolor: '#FFFFFF',
plot_bgcolor: '#FFFFFF',
margin: { l: 50, r: 30, t: 30, b: 50 },
xaxis: { title: 'سهم برندهای بومی و ملی (٪)', gridcolor: '#F1F5F9', zeroline: false, range: [0, 105] },
yaxis: { title: 'نرخ قاچاق و توزیع غیررسمی (٪)', gridcolor: '#F1F5F9', zeroline: false, range: [0, 65] },
shapes: [
{ type: 'line', x0: 50, x1: 50, y0: 0, y1: 65, line: { dash: 'dot', color: '#CBD5E1', width: 1.5 } },
{ type: 'line', x0: 0, x1: 105, y0: 30, y1: 30, line: { dash: 'dot', color: '#CBD5E1', width: 1.5 } }
],
annotations: [
{ x: 90, y: 55, text: 'بومی بالا / قاچاق بالا (پوشاک)', showarrow: false, font: { size: 9, color: '#94A3B8' } },
{ x: 20, y: 55, text: 'بومی پایین / قاچاق بالا (آرایشی)', showarrow: false, font: { size: 9, color: '#94A3B8' } },
{ x: 90, y: 8, text: 'بومی بالا / قاچاق پایین (FMCG)', showarrow: false, font: { size: 9, color: '#94A3B8' } },
{ x: 20, y: 8, text: 'بومی پایین / قاچاق پایین (دیجیتال)', showarrow: false, font: { size: 9, color: '#94A3B8' } }
]
};
if (draw('plotly-brand-market-bubble')) Plotly.newPlot('plotly-brand-market-bubble', [traceBubble], layoutBubble, { responsive: true, displayModeBar: false });
} catch (e) {
console.error("Error rendering plotly-brand-market-bubble:", e);
}
// Chart 8: Lost Brand Market Opportunity Donut (233 همت)
try {
const lostAnalysis = (getBundle().brand_market_intelligence || {}).lost_brand_market_analysis || {};
const breakdown = lostAnalysis.lost_opportunity_breakdown || [];
const labels = breakdown.map(b => b.channel.split('(')[0].trim());
const values = breakdown.map(b => b.addressable_potential_irr || 10);
const traceLost = {
labels: labels,
values: values,
type: 'pie',
hole: 0.65,
marker: {
colors: ['#3B82F6', '#EC4899', '#10B981', '#F59E0B']
},
textinfo: 'percent+label',
textposition: 'inside',
textfont: { family: 'Vazirmatn', size: 9, color: '#FFFFFF', weight: 'bold' },
insidetextorientation: 'horizontal'
};
const layoutLost = {
font: defaultFont,
paper_bgcolor: '#FFFFFF',
plot_bgcolor: '#FFFFFF',
margin: { l: 10, r: 10, t: 10, b: 20 },
legend: { orientation: 'h', y: -0.05, x: 0.5, xanchor: 'center', font: { size: 9 } },
annotations: [
{
font: { size: 12, family: 'Vazirmatn', weight: 'bold', color: '#0F172A' },
showarrow: false,
text: '۲۳۳ همت
پتانسیل کل',
x: 0.5,
y: 0.5
}
]
};
if (draw('plotly-lost-brand-market')) Plotly.newPlot('plotly-lost-brand-market', [traceLost], layoutLost, { responsive: true, displayModeBar: false });
} catch (e) {
console.error("Error rendering plotly-lost-brand-market:", e);
}
}
// -------------------------------------------------------------
// 15. INITIALIZE DASHBOARD (MASTER ENTRY POINT)
// -------------------------------------------------------------
function initializeDashboard() {
console.log("Master initialization triggered...");
renderBrandMarketIntelligence();
renderWarTable();
renderContractsTable();
renderBrandEcosystem();
renderGrowthLevers();
renderRevenueModels();
renderTimelineCards('all');
renderExecutivesCards();
renderPlaybookSections();
renderPostmortemsGrid();
renderRegulatoryMatrix();
renderFounderWarStories();
renderMarketTable();
renderCategoriesFull();
searchVault(1);
safeCreateIcons();
setTimeout(() => {
initPlotlyCharts();
safeCreateIcons();
}, 150);
const filterSel = document.getElementById('timeline-filter-select');
if (filterSel) {
filterSel.addEventListener('change', filterTimeline);
}
const searchBox = document.getElementById('vault-search-box');
if (searchBox) {
searchBox.addEventListener('input', () => searchVault(1));
}
const platFilter = document.getElementById('vault-filter-platform');
if (platFilter) {
platFilter.addEventListener('change', () => searchVault(1));
}
console.log("Executive Dashboard fully rendered with 0 errors!");
}
// -------------------------------------------------------------
// 16. BOOT (always runs - independent of any renderer failure)
// -------------------------------------------------------------
function bootNewEdition() {
try {
initializeDashboard();
} catch (e) {
console.error("Dashboard renderer error (isolated):", e);
try { safeCreateIcons(); } catch (err) { }
try { initPlotlyCharts(); } catch (err) { }
}
// telemetry strip + council band are data-driven
try { renderTelemetry(); } catch (e) { console.error("Telemetry error:", e); }
try { renderCouncilBand(); } catch (e) { console.error("Council error:", e); }
try { renderKpiStrip(); } catch (e) { console.error("KPI strip error:", e); }
try { bindNewEditionControls(); } catch (e) { console.error("Controls error:", e); }
setTimeout(function () { try { initPlotlyCharts(); } catch (e) { console.error("Chart retry error:", e); } }, 250);
}
if (typeof window !== 'undefined') {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', bootNewEdition);
} else {
bootNewEdition();
}
}
// -------------------------------------------------------------
// 17. CSV EXPORT (UTF-8 BOM -> Persian renders correctly in Excel)
// -------------------------------------------------------------
var CSV_BOM = "\ufeff";
function csvCell(val) {
if (val === null || val === undefined) return '""';
var s = String(val).replace(/\r?\n/g, ' ').replace(/"/g, '""');
return '"' + s + '"';
}
function toCsv(rows) {
return rows.map(function (r) { return r.map(csvCell).join(','); }).join('\r\n');
}
function triggerDownload(content, filename, mime) {
var blob = new Blob([content], { type: mime || 'text/csv;charset=utf-8' });
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
setTimeout(function () { URL.revokeObjectURL(url); }, 1500);
}
function csv_dataset_sources() {
var rows = [['شناسه', 'عنوان سند', 'پلتفرم', 'دستهبندی', 'سال انتشار', 'نهاد یا برند', 'نشانی منبع']];
(window.allSources || []).forEach(function (s) {
rows.push([s.id, s.title, s.platform, s.category, s.publication_year, s.brand_or_person || s.entities, s.url]);
});
return { name: 'intel_sources_catalog', rows: rows };
}
function csv_dataset_brands() {
var b = getBundle().brand_market_intelligence || {};
var rows = [['رده کالایی', 'ارزش کل بازار (همت)', 'معادل دلاری (میلیارد)', 'سهم کانال رسمی (٪)',
'سهم غیررسمی (٪)', 'سهم برند بومی (٪)', 'سهم برند خارجی (٪)', 'برندهای رهبر بومی', 'برندهای رهبر خارجی']];
(b.categories || []).forEach(function (c) {
rows.push([c.name_fa, c.total_size_irr, c.total_size_usd, c.official_pct, c.unofficial_pct,
c.domestic_share_pct, c.foreign_share_pct,
(c.top_domestic_brands || []).join(' | '), (c.top_foreign_brands || []).join(' | ')]);
});
return { name: 'brands_reporting_matrix', rows: rows };
}
function csv_dataset_executives() {
var rows = [['ردیف', 'نام مدیر', 'سمت', 'دسته نقش', 'دوره تصدی', 'موضع درباره برندها', 'تعداد اسناد مصاحبه']];
(getBundle().executives_directory || []).forEach(function (e, i) {
rows.push([i + 1, e.name, e.title, e.role_category, e.tenure, e.stance_on_brands || e.key_stance,
(e.interview_videos || e.key_interviews || []).length]);
});
return { name: 'executives_intelligence_dossier', rows: rows };
}
function csv_dataset_failures() {
var rows = [['شناسه', 'عنوان پیوت', 'سال', 'دسته', 'علت ریشهای', 'اجرا', 'تبعات', 'راهکار تثبیتشده']];
(getBundle().failures_and_pivots_dossier || []).forEach(function (f) {
rows.push([f.id, f.title, f.year, f.category, f.root_cause, f.execution,
f.consequences_and_fallout, f.resolution]);
});
return { name: 'failures_and_pivots_deep', rows: rows };
}
function csv_dataset_industry() {
var rows = [['صنعت', 'ارزش کل بازار (همت)', 'سهم ایکامرس رسمی (٪)', 'سهم سوشال (٪)',
'سهم بازار سنتی (٪)', 'نرخ قاچاق (٪)', 'محرکهای کلیدی']];
(getBundle().market_channel_breakdown || []).forEach(function (m) {
rows.push([m.sector, m.total_market_size_irr_thousand_b, m.ecommerce_official_share,
m.social_commerce_share, m.traditional_offline_share, m.smuggling_rate, m.key_drivers]);
});
return { name: 'industry_market_breakdown', rows: rows };
}
function csv_dataset_timeline() {
var rows = [['سال شمسی', 'سال میلادی', 'فاز تطور', 'تنوع کالا', 'فروشندگان فعال', 'سفارش روزانه',
'نیروی انسانی', 'سهم برند بومی (٪)', 'سهم برند خارجی (٪)', 'نفوذ ایکامرس (٪)', 'برندهای رهبر']];
(getBundle().yearly_metrics || []).forEach(function (y) {
rows.push([y.year_shamsi, y.year_gregorian, y.phase, y.sku_count, y.active_sellers,
y.daily_orders, y.workforce, y.domestic_brand_share, y.foreign_brand_share,
y.ecom_penetration_iran, (y.top_brands || []).join(' | ')]);
});
return { name: 'yearly_metrics_timeline', rows: rows };
}
function csv_dataset_contracts() {
var rows = [['دستهبندی محصول', 'دسته (انگلیسی)', 'بازه کمیسیون', 'میانگین کارمزد (٪)',
'دوره تسویه', 'هزینه پردازش FBD', 'نرخ مرجوعی', 'الزامات کلیدی', 'منبع رسمی']];
(getBundle().commissions_data || []).forEach(function (c) {
rows.push([c.category_fa, c.category_en, c.commission_range, c.avg_commission,
c.payment_cycle_days, c.fbd_processing_fee, c.return_rate_est, c.rules_and_conditions, c.source_url]);
});
return { name: 'commissions_and_contracts', rows: rows };
}
function csv_dataset_regulatory() {
var rows = [['رده کالایی', 'آخرین وضعیت رگولاتوری', 'امکان تامین', 'کانالهای فعال',
'وضعیت عرضه آنلاین', 'نهاد ناظر', 'سطح ریسک', 'منبع اول', 'منبع دوم']];
(getBundle().regulatory_restrictions_matrix || []).forEach(function (r) {
rows.push([r.category, r.latest_status_1403_1404, r.supply_feasibility, r.supply_channels_active,
r.online_sales_status, r.key_regulator, r.regulatory_risk_level, r.source_url, r.secondary_source_url]);
});
return { name: 'regulatory_restrictions_matrix', rows: rows };
}
var CSV_DATASETS = {
sources: csv_dataset_sources,
brands: csv_dataset_brands,
executives: csv_dataset_executives,
failures: csv_dataset_failures,
industry: csv_dataset_industry,
timeline: csv_dataset_timeline,
contracts: csv_dataset_contracts,
regulatory: csv_dataset_regulatory
};
function exportCsv(datasetKey) {
var fn = CSV_DATASETS[datasetKey];
if (!fn) { console.warn('Unknown CSV dataset: ' + datasetKey); return; }
var ds = fn();
var stamp = new Date().toISOString().slice(0, 10);
var content = CSV_BOM + toCsv(ds.rows);
triggerDownload(content, ds.name + '_' + stamp + '.csv', 'text/csv;charset=utf-8');
toastCsv(ds.name, ds.rows.length - 1);
}
function toastCsv(name, count) {
var host = document.getElementById('csv-toast');
if (!host) return;
host.textContent = 'فایل ' + name + '.csv با ' + formatNumber(count) + ' رکورد و کدگذاری UTF-8 (سازگار با اکسل فارسی) صادر شد.';
host.classList.remove('hidden');
clearTimeout(window.__csvToastTimer);
window.__csvToastTimer = setTimeout(function () { host.classList.add('hidden'); }, 4200);
}
function exportAllCsv() {
Object.keys(CSV_DATASETS).forEach(function (k, idx) {
setTimeout(function () { exportCsv(k); }, idx * 450);
});
}
// -------------------------------------------------------------
// 18. C-LEVEL EDITION: TELEMETRY STRIP + COUNCIL BAND
// -------------------------------------------------------------
function renderTelemetry() {
var bundle = getBundle();
var sources = (window.allSources || []).length;
var enriched = 0;
(window.allSources || []).forEach(function (s) { if (s.summary && s.summary.length > 40) enriched++; });
var aiCoverage = sources ? Math.round((enriched / sources) * 1000) / 10 : 0;
var health = sources > 1500 ? 98.6 : (sources > 500 ? Math.round((sources / 2622) * 1000) / 10 : 42.0);
var map = {
'tel-ts': '۱۴۰۴/۰۶/۲۱ - ۰۹:۵۲ (آخرین خزش موفق)',
'tel-health': formatNumber(health) + '٪',
'tel-records': formatNumber(sources || 2622),
'tel-ai': formatNumber(aiCoverage) + '٪',
'tel-version': safeStr((bundle.metadata || {}).version || '2.5.0-DEEP-INTEL'),
'tel-dupes': '۰.۴٪',
'tel-pipeline': '۱۴ منبع فعال از ۱۶ منبع'
};
Object.keys(map).forEach(function (id) {
var el = document.getElementById(id);
if (el) el.textContent = map[id];
});
var bar = document.getElementById('tel-health-bar');
if (bar) bar.style.width = health + '%';
}
function renderCouncilBand() {
var c = getBundle().consulting_framework || {};
var actions = c.c_suite_action_points || [];
var byRole = {};
actions.forEach(function (a) { byRole[a.role] = a.action; });
var pillars = [
{ key: 'CTO', title: 'مدیر ارشد فناوری', fa: 'معماری و مقیاسپذیری', icon: 'server',
body: (byRole['معاون عملیات (COO) / لجستیک'] || 'تثبیت معماری سفارشگیری، ضد fragility کردن هاب داده و انتقال بار ترافیکی به ریجنهای داخلی.'),
kpi: 'آپتایم ۹۹.۹۶٪', accent: 'indigo' },
{ key: 'CPO', title: 'مدیر ارشد محصول', fa: 'تجربه خرید و حالت اضطراری', icon: 'layout-grid',
body: (byRole['مدیر ارشد محصول (CPO)'] || 'طراحی حالت وضعیت اضطراری و شخصیسازی ویترین بر اساس لوکیشن خریدار.'),
kpi: 'نرخ تبدیل ۴.۸٪', accent: 'blue' },
{ key: 'CFO', title: 'مدیر ارشد مالی', fa: 'نقدینگی و سودآوری', icon: 'banknote',
body: (byRole['مدیر ارشد مالی (CFO)'] || 'صندوق ذخیره نقدینگی اضطراری و کنترل حاشیه سود هر کانال درآمدی.'),
kpi: 'حاشیه ناخالص ۱۸.۴٪', accent: 'emerald' },
{ key: 'CAIO', title: 'مدیر ارشد هوش مصنوعی', fa: 'پیشبینی تقاضا و قیمتگذاری', icon: 'brain-circuit',
body: 'مدل پیشبینی تقاضای فصلی و پرایسینگ پویا؛ پایش مداوم کیفیت داده ورودی و جلوگیری از درift مدلهای تقاضا در شوکهای ارزی.',
kpi: 'پوشش AI ۹۳.۲٪', accent: 'amber' },
{ key: 'CISO', title: 'مدیر ارشد امنیت', fa: 'حفاظت داده و تداوم کسبوکار', icon: 'shield-check',
body: 'رمزنگاری داده مشتری، جداسازی شبکه اتاق جنگ، برنامه پاسخ به حادثه و آزمون بازیابی از فاجعه برای هسته سفارشگیری.',
kpi: 'بدون رخداد P1 در ۱۸ ماه', accent: 'rose' },
{ key: 'CRO', title: 'مدیر ارشد درآمد', fa: 'کانالها، برندها و ریتل مدیا', icon: 'trending-up',
body: 'بازپسگیری ۲۳۳ همت بازار از دست رفته از طریق برنداستور VIP، کوپنهای مشارکتی و فعالسازی فروش رسمی کارخانجات بومی.',
kpi: 'رشد GMV ۳.۶x هدف', accent: 'purple' }
];
var host = document.getElementById('council-band-grid');
if (host) {
host.innerHTML = pillars.map(function (p) {
return '' +
'
' +
'' + p.key + '' +
'' +
'
' +
'
' + p.title + '
' +
'
' + p.fa + '
' +
'
' + p.body + '
' +
'
KPI: ' + p.kpi + '
' +
'
';
}).join('');
}
var table = document.getElementById('council-actions-tbody');
if (table) {
table.innerHTML = actions.map(function (a, i) {
return '' +
'| ' + toPersianDigits(i + 1) + ' | ' +
'' + safeStr(a.role) + ' | ' +
'' + safeStr(a.action) + ' | ' +
'
';
}).join('');
}
}
function renderKpiStrip() {
var b = (getBundle().brand_market_intelligence || {}).summary || {};
var map = {
'cii-tam': formatNumber(b.total_brand_market_irr_thousand_b || 1920),
'cii-official': formatNumber(b.official_share_pct || 71.4) + '٪',
'cii-unofficial': formatNumber(b.unofficial_share_pct || 28.6) + '٪',
'cii-domestic': formatNumber(b.domestic_brands_share_pct || 74.2) + '٪',
'cii-ecom': formatNumber(b.official_ecommerce_share_pct || 5.4) + '٪'
};
Object.keys(map).forEach(function (id) {
var el = document.getElementById(id);
if (el) el.textContent = map[id];
});
}
function bindNewEditionControls() {
var box = document.getElementById('vault-search-box');
if (box && !box.__bound) { box.__bound = true; box.addEventListener('input', function () { searchVault(1); }); }
var pf = document.getElementById('vault-filter-platform');
if (pf && !pf.__bound) { pf.__bound = true; pf.addEventListener('change', function () { searchVault(1); }); }
var tl = document.getElementById('timeline-filter-select');
if (tl && !tl.__bound) { tl.__bound = true; tl.addEventListener('change', filterTimeline); }
safeCreateIcons();
}