/* Ekeepa Financial v02 — data-driven static dashboard. Monetary values: million toman. */
(() => {
'use strict';
const $ = (s) => document.querySelector(s);
const fa = (value, digits = 0) => {
if (value === undefined || value === null || value === '') return '—';
const n = Number(value);
if (!Number.isFinite(n)) return '—';
return new Intl.NumberFormat('fa-IR', { maximumFractionDigits: digits, minimumFractionDigits: digits }).format(n);
};
const money = (v, digits = 0) => `${fa(v, digits)} م.ت`;
const billion = (v) => `${fa(v / 1000, 1)} میلیارد`;
const esc = (v) => String(v ?? '').replace(/[0-9]/g, d => '۰۱۲۳۴۵۶۷۸۹'[d]).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
const rowMap = (data) => Object.fromEntries((data.rows || []).map((r) => [r.key, r]));
const total = (r) => r ? Number(r?.total ?? (r?.values || []).reduce((a, b) => a + Number(b || 0), 0)) : NaN;
const val = (scenario, key) => scenario?.[key];
function renderHero(data, rows) {
$('#period').textContent = data.period || 'مدل ۱۲ماهه';
const base = (data.scenarios || []).find((s) => /base|پایه/i.test(s.name || '')) || data.scenarios?.[0] || {};
const items = [
['درآمد سال مدل', billion(val(base, 'revenue') ?? total(rows.revenue)), 'جمع ۱۲ ماه'],
['سود عملیاتی پیش از مالیات', billion(val(base, 'operating') ?? total(rows.operating)), 'برآورد سالانه'],
['سود پس از مالیات', billion(val(base, 'afterTax') ?? total(rows.afterTax)), 'برآورد سالانه'],
['دور پیشنهادی', billion(data.assumptions?.find((a) => a.key === 'round')?.value), 'مفروض تامین مالی؛ نه دور لازم']
];
$('#hero-kpis').innerHTML = items.map(([l, n, note]) => `${l}${n}${note}`).join('');
}
function renderMonthly(data) {
const months = data.months || [];
const rows = data.rows || [];
const preferred = ['gmv', 'revenue', 'b2b_cogs', 'hr', 'infra', 'marketing', 'cost', 'operating', 'tax', 'afterTax', 'collections', 'receivables', 'cashflow', 'cash'];
const ordered = [...rows].sort((a, b) => {
const ai = preferred.indexOf(a.key), bi = preferred.indexOf(b.key);
return (ai < 0 ? 99 : ai) - (bi < 0 ? 99 : bi);
});
$('#monthly-table thead').innerHTML = `
| شاخص | ${months.map((m) => `${esc(m)} | `).join('')}جمع / پایان |
`;
$('#monthly-table tbody').innerHTML = ordered.map((r) => {
const ending = ['cash', 'receivables'].includes(r.key);
return `| ${esc(r.label)} | ${(r.values || []).map((x) => `${money(x)} | `).join('')}${money(ending ? r.values?.at(-1) : total(r))} |
`;
}).join('');
}
function renderCharts(data, rows) {
if (!window.Plotly) { $('#operating-chart').style.display='none'; $('#cash-chart').style.display='none'; $('#operating-fallback').style.display = 'block'; $('#cash-fallback').style.display = 'block'; return; }
const months = data.months || [];
const common = { responsive: true, displayModeBar: false, locale: 'fa' };
const layout = (title) => ({ title: { text: title, font: { family: 'Vazirmatn', size: 12, color: '#475569' }, x: .98, xanchor: 'right' }, font: { family: 'Vazirmatn', color: '#475569' }, paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', margin: { l: 55, r: 12, t: 38, b: 55 }, hoverlabel: { font: { family: 'Vazirmatn' } }, xaxis: { tickfont: { size: 10 }, gridcolor: 'rgba(0,0,0,0)' }, yaxis: { tickfont: { size: 10 }, gridcolor: '#e2e8f0', zerolinecolor: '#94a3b8' }, legend: { orientation: 'h', y: 1.18, x: 1, xanchor: 'right', font: { size: 11 } } });
const series = (r) => r?.values || Array(months.length).fill(0);
Plotly.newPlot('operating-chart', [
{ x: months, y: series(rows.revenue), type: 'scatter', mode: 'lines+markers', name: 'درآمد', line: { color: '#4f46e5', width: 3 }, marker: { size: 5 }, hovertemplate: '%{x}
درآمد: %{y:,.0f} م.ت' },
{ x: months, y: series(rows.operating), type: 'bar', name: 'سود عملیاتی', marker: { color: '#14b8a6' }, hovertemplate: '%{x}
سود عملیاتی: %{y:,.0f} م.ت' }
], layout('درآمد و سود عملیاتی ماهانه'), common);
Plotly.newPlot('cash-chart', [
{ x: months, y: series(rows.cashflow), type: 'bar', name: 'جریان نقد', marker: { color: '#818cf8' }, hovertemplate: '%{x}
جریان نقد: %{y:,.0f} م.ت' },
{ x: months, y: series(rows.cash), type: 'scatter', mode: 'lines+markers', name: 'مانده نقد', line: { color: '#047857', width: 3 }, marker: { size: 5 }, hovertemplate: '%{x}
مانده نقد: %{y:,.0f} م.ت' }
], layout('نقدینگی ماهانه'), common);
}
function renderScenarios(data) {
const scenarios = data.scenarios || [];
const tabbar = $('#scenario-tabs'), detail = $('#scenario-detail');
const render = (s) => {
const parameters = [['نرخ', s.rate], ['B2B', s.b2b], ['حجم', s.volume], ['هزینه', s.cost]].filter(([, x]) => x !== undefined && x !== null).map(([k, x]) => `${k}: ${esc(x)}`).join(' · ');
const metrics = [['GMV', s.gmv], ['درآمد', s.revenue], ['سود عملیاتی', s.operating], ['مالیات برآوردی', s.tax], ['پس از مالیات', s.afterTax], ['حداقل نقد', s.minCash], ['نقد پایان دوره', s.endCash], ['دور لازم', s.requiredRound]];
detail.innerHTML = `سناریوی انتخابشده${esc(s.name || 'سناریو')}
${parameters || 'پارامترهای سناریو در فایل داده ثبت نشدهاند.'}
${metrics.map(([l, x]) => `
${l}${money(x)}
`).join('')}
`;
};
tabbar.innerHTML = scenarios.map((s, i) => ``).join('');
tabbar.addEventListener('click', (e) => { const b = e.target.closest('button'); if (!b) return; tabbar.querySelectorAll('button').forEach((x) => { x.setAttribute('aria-selected', x === b ? 'true' : 'false'); x.setAttribute('aria-pressed', x === b ? 'true' : 'false'); }); render(scenarios[Number(b.dataset.index)]); });
if (scenarios.length) render(scenarios[0]); else detail.innerHTML = 'سناریویی در data.json ثبت نشده است.
';
}
function renderAssumptions(data) {
$('#assumption-list').innerHTML = (data.assumptions || []).map((a) => `${esc(a.label)}${esc(a.value)}${a.note ? `${esc(a.note)}` : ''}`).join('') || 'مفروضات—';
$('#talent-table thead').innerHTML = '| نقش | فاز | حقوق | کارمزد جذب | ESOP |
';
$('#talent-table tbody').innerHTML = (data.talent || []).map((x) => `| ${esc(x.role)} | ${esc(x.phase)} | ${money(x.salary)} | ${money(x.agency)} | ${esc(x.esop)} |
`).join('') || '| داده برنامه تیم ثبت نشده است. |
';
}
function renderGovernance(data) {
const list = (items, target, titleKey, textKey) => $(target).innerHTML = (items || []).map((x) => `${esc(x[titleKey])}${esc(x[textKey] || '')}
`).join('') || 'موردی ثبت نشده است.
';
list(data.notes, '#notes-list', 'title', 'text'); list(data.sources, '#sources-list', 'name', 'note');
$('#checks-list').innerHTML = (data.checks || []).map((x) => `${esc(x.name)}`).join('') || 'کنترلهای مدل ثبت نشده است.';
}
async function start() {
try {
const response = await fetch('data.json', { cache: 'no-store' });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
const rows = rowMap(data);
renderHero(data, rows); renderMonthly(data); renderScenarios(data); renderAssumptions(data); renderGovernance(data);
$('#inputs-table thead').innerHTML = `| ورودی | ${data.months.map(m => `${esc(m)} | `).join('')}یادداشت / واحد |
`;
$('#inputs-table tbody').innerHTML = (data.inputs || []).map(r => `| ${esc(r.label)} | ${r.values.map(v => `${fa(v, 2)} | `).join('')}${esc(r.note)} |
`).join('');
try { renderCharts(data, rows); } catch (e) { ['operating','cash'].forEach(k => { document.getElementById(k+'-chart').style.display='none'; document.getElementById(k+'-fallback').style.display='block'; }); }
} catch (error) {
console.error('data.json load failed:', error);
$('#period').textContent = 'data.json هنوز در این مسیر موجود نیست.';
$('#hero-kpis').innerHTML = 'وضعیت مدلداده یافت نشدپس از قرار گرفتن data.json، داشبورد خودکار بارگذاری میشود.';
['#operating-fallback','#cash-fallback'].forEach((s) => { $(s).style.display = 'block'; });
}
}
start();
})();