Merge origin/main into codex/ddos-scaling-and-mitigation

This commit is contained in:
Frederic Jung 2026-10-27 13:21:51 +00:00
commit e7ae3b18bf
154 changed files with 19102 additions and 14323 deletions

View file

@ -0,0 +1,30 @@
/* ---------- scenario and level progress (#34) ---------- */
// Red Sea Crisis (#113): traffic your links carry into and out of Asia, and how long it has stayed above the goal.
const RS_G=80,RS_DAYS=30,asiaG=()=>S.links.reduce((a,l)=>a+((CITY[l.a].reg==='AS')!==(CITY[l.b].reg==='AS')?(R.load[l.id]||0):0),0);
const pSrv=g=>({l:tr('common.traffic_served'),v:R.served,max:g,txt:`${fmtG(R.served)} / ${fmtG(g)}`});
const pReach=()=>({l:tr('common.reach'),v:R.reach,max:0.99,txt:`${pct(R.reach)} / 99%`});
const pChk=(l,ok)=>({l,v:ok?1:0,max:1,txt:ok?'✓':'—'});
const SCN_PROG={stg:()=>[{l:tr('common.reach'),v:R.reach,max:0.45,txt:`${pct(R.reach)} / 45%`},pSrv(300)],redsea:()=>{const g=asiaG(),n=S.stats.asiaRun||0;return [pChk(tr('progress.a_path_from_marseille_to_singapore'),pathExists('mrs','sin')),{l:tr('progress.your_traffic_to_and_from_asia'),v:Math.min(g,RS_G),max:RS_G,txt:`${fmtG(g)} / ${fmtG(RS_G)}`},{l:tr('progress.days_in_a_row_at_g',{g:fmtG(RS_G)}),v:n,max:RS_DAYS,txt:`${n} / ${RS_DAYS}`}];},spat:()=>[pReach(),pSrv(150)],
carnaval:()=>[pChk(tr('progress.carnaval_delivered_in_full'),(S.stats.evFull||0)>=1)],ixbr:()=>{const n=brIxN();return [{l:tr('progress.ix_brrr_ports'),v:n,max:15,txt:`${n} / 15`},pChk(tr('progress.a_port_on_ix_brrr_manaus'),S.ixp.mao!==undefined),pSrv(200)];},
c2c:()=>[pChk(tr('progress.a_path_from_cape_town_to'),pathExists('cpt','cai')),...['lag','nbo'].map(c=>pChk(tr('progress.pop_in_city',{city:CITY[c].name}),!!S.pops[c])),pSrv(150)],
pac:()=>[pChk(tr('progress.1_6t_on_every_hop_from'),fastPath('lax','syd',1600)),pChk(tr('progress.a_path_from_los_angeles_to'),pathExists('lax','tok')),pSrv(150)],
atl:()=>[pChk(tr('progress.1_6t_on_every_hop_from_a90b'),fastPath('mia','mad',1600)),pChk(tr('progress.1_6t_on_every_hop_from_da01'),fastPath('lis','lag',1600)),pSrv(100)],
darien:()=>[...['bog','lim','scl','sao'].map(c=>pChk(tr('progress.pop_in_city',{city:CITY[c].name}),!!S.pops[c])),pSrv(150)],
gangnam:()=>[pReach(),pSrv(200)],
fttb:()=>[...AU_BB.map(c=>pChk(tr('progress.broadband_in_city',{city:CITY[c].name}),!!(S.pops[c]&&S.pops[c].bb))),{l:tr('common.cables_overseas'),v:Math.min(2,auExits()),max:2,txt:`${auExits()} / 2`}],
flood:()=>{const ok=S.stats.ddosOk||0,big=S.stats.ddosOkBig||0,attacks=ddosAll();
return [{l:tr('common.floods_held'),v:ok,max:20,txt:`${ok} / 20`},{l:tr('progress.terabit_floods_held'),v:big,max:5,txt:`${big} / 5`},{l:tr('progress.floods_that_got_through'),v:0,max:0,txt:String(S.stats.ddosLost||0)}].concat(attacks.map(a=>({l:tr('progress.under_attack_now'),v:0,max:0,txt:`${fmtG(a.gbps)} · ${CITY[a.city].name} · ${pct(a.worst===undefined?1:a.worst)}`})));},baltic:()=>[{l:tr('progress.days_in_a_row_with_99'),v:S.stats.clean||0,max:90,txt:tr('progress.n_of_m',{n:S.stats.clean||0,m:90})}]};
function scnProg(){const sc=S&&S.scn;if(!sc)return null;
if(sc.id==='weekly')return {goal:tr('common.serve_as_much_traffic_as_you'),items:[{l:tr('progress.your_score_peak_traffic'),v:0,max:0,txt:fmtG(S.stats.peak||0)}],f:Math.min(1,S.day/sc.days)};
const def=SCN.find(x=>x.id===sc.id),fn=SCN_PROG[sc.id];if(!def)return null;let items=[];try{items=fn?fn():[];}catch(e){items=[];}
const meas=items.filter(x=>x.max),f=sc.done?1:meas.length?meas.reduce((a,x)=>a+Math.min(1,x.v/x.max),0)/meas.length:0;return {goal:def.goal,items,f};}
const pRow=x=>`<div class="kv"><span>${esc(x.l)}</span><b>${esc(x.txt)}</b></div>${x.max?`<div class="bar ${x.v>=x.max?'':'warn'}"><i style="width:${Math.min(100,x.max?x.v/x.max*100:0)}%"></i></div>`:''}`;
function scnCard(){const sc=S.scn,P=scnProg();if(!sc||!P)return '';const left=Math.max(0,sc.days-S.day);
const st=sc.done?`<b style="color:var(--eye)">${tr('progress.done_in_d_days',{d:sc.done})}</b>`:sc.failed?`<b style="color:var(--bad)">${tr('common.time_s_up')}</b>`:tr('common.n_days_left',{n:left});
return `<div class="pcard"><div class="eyebrow">${tr('common.scenario')} · ${Math.round(P.f*100)}%</div><div class="pt">${esc(sc.name)}</div><div class="meta">🎯 ${esc(P.goal)}</div>${P.items.map(pRow).join('')}<div class="kv"><span>${tr('common.time')}</span><b>${st}</b></div><div class="bar ${!sc.done&&left<sc.days*0.2?'bad':''}"><i style="width:${Math.min(100,S.day/sc.days*100)}%"></i></div></div>`;}
function lvlItems(){const lv=S.lvl||1,pk=S.stats.peak||0,pops=Object.keys(S.pops).length,G=(l,v,max,txt)=>({l,v,max,txt}),q=LV_REQ[lv];if(!q)return [];
const out=[G(tr('common.peak_traffic'),pk,q.pk,`${fmtG(pk)} / ${fmtG(q.pk)}`),G(tr('common.pops'),pops,q.pops,`${pops} / ${q.pops}`)],rg=lvReg(lv);if(rg)out.push(G(tr('common.continents'),regionsCount(),rg,`${regionsCount()} / ${rg}`));return out;}
// Lost Tier 1 status explains itself where you look for it, not only in a toast you may have missed (#73).
const t1Note=()=>S.won&&!isTier1()?`<p class="why">${tr('progress.not_tier_1_right_now_why',{why:esc(t1Why())})}</p>`:'';
function lvlCard(){const lv=S.lvl||1,nx=LEVELS[lv];
return `<div class="pcard lv"><div class="eyebrow">${tr('progress.customer_level_lv_of_max',{lv,max:LEVELS.length})}</div><div class="pt">${esc(LEVELS[lv-1].n)}</div><div class="meta"><i>${esc(LEVELS[lv-1].q)}</i></div>${t1Note()}${nx?`<div class="meta">${tr('progress.next_name_unlocks_what',{name:esc(nx.n),what:esc(lc1(nx.unlock))})}</div>${lvlItems().map(pRow).join('')}`:`<div class="meta">${tr('common.every_customer_type_is_unlocked_go')}</div>`}</div>`;}

View file

@ -0,0 +1,31 @@
/* ---------- where to meet a network (#12, #111, #121) ---------- */
// Static: the cities where a network takes PNIs and the exchanges it sits on. Built once, on first use.
let PLACES=null;
function netPlaces(id){if(!PLACES){PLACES={};for(const n of NETS)PLACES[n.id]={p:n.pops.filter(c=>CITY[c]&&!CITY[c].off),x:[]};
for(const c of CITIES)if(c.ix&&!c.off)for(const n of NETS)if(n.ix==='ALL'||(Array.isArray(n.ix)&&n.ix.includes(c.id)))PLACES[n.id].x.push(c.id);
for(const X of XIX)for(const m of X.members)if(PLACES[m])PLACES[m].x.push(X.id);}return PLACES[id];}
// km from each city to your nearest POP, cached until the set of POPs changes.
let NEARK='',NEARM=null;
function popNear(){const ps=Object.keys(S.pops),k=ps.join();if(k!==NEARK||!NEARM){NEARK=k;NEARM={};for(const c of CITIES)NEARM[c.id]=ps.length?Math.min(...ps.map(q=>q===c.id?0:kmBetween(q,c.id))):0;}return NEARM;}
// One entry per city: can you PNI there, which of its exchanges have them. Your POPs first, then nearest.
let SPOTK='',SPOTM={};
function meetSpots(id){const near=popNear();if(SPOTK!==NEARK){SPOTK=NEARK;SPOTM={};}if(SPOTM[id])return SPOTM[id];const P=netPlaces(id),m={};if(!P)return [];
for(const c of P.p)(m[c]||(m[c]={c,pni:false,ix:[]})).pni=true;
for(const x of P.x){const c=ixCity(x);if(CITY[c])(m[c]||(m[c]={c,pni:false,ix:[]})).ix.push(x);}
return SPOTM[id]=Object.values(m).sort((a,b)=>(!!S.pops[b.c]-!!S.pops[a.c])||(near[a.c]-near[b.c])||(a.c<b.c?-1:1));}
function meetLine(n,max){const sp=meetSpots(n.id);if(!sp.length)return '';
const lab=x=>[x.pni?'PNI':'',...x.ix.map(ixName)].filter(Boolean).join(' · ');
return `<div class="meta" style="margin-top:4px"><b>${tr('meet_a_network.where_to_meet_them')}</b></div><div class="btns">${sp.slice(0,max).map(x=>btn(`${esc(CITY[x.c].name)} <small>${esc(lab(x))}</small>`,'meetGo',{city:x.c},S.pops[x.c]?'sm':'ghost sm')).join('')}${sp.length>max?btn(tr('dashboard.n_more',{n:sp.length-max}),'netFocus',{id:n.id},'ghost sm'):''}</div>`;}
// The nearest place to meet a network you have no POP for, for one-line hints.
function nearestSpot(id){const x=meetSpots(id)[0];return x&&!S.pops[x.c]?x:null;}
// Networks you reach only through transit, biggest first: what stands between you and Tier 1.
const ntLost=()=>NETS.filter(n=>!R.nt[n.id]).sort((a,b)=>NSH[b.id]-NSH[a.id]);
function t1Card(){const cur=GOALS.find(g=>S.done[g.id]===undefined);if(!((cur&&cur.id==='t1')||S.won)||isTier1())return '';
const need=t1Need(),miss=need.filter(n=>!S.pni.some(p=>p.net===n.id&&pniOn(p))),club=t1Club(),lost=ntLost(),nb=n=>btn(esc(n.name),'netFocus',{id:n.id},'ghost sm');
let h=`<div class="pcard"><div class="eyebrow">${tr('common.goal')} · ${tr('common.go_transit_free_tier_1')}</div><div class="pt">${tr('meet_a_network.road_to_tier_1')}</div>`;
h+=pRow({l:tr('meet_a_network.transit_ports_to_cancel'),v:S.transit.length?0:1,max:1,txt:S.transit.length?String(S.transit.length):'✓'});
h+=pRow({l:tr('meet_a_network.pnis_with_every_tier_1'),v:need.length-miss.length,max:need.length,txt:`${need.length-miss.length} / ${need.length}`});
if(miss.length)h+=`<div class="btns">${miss.map(nb).join('')}</div>`+(club.ok?'':`<p class="why">${tr('meet_a_network.tier_1s_only_take_a_pni',{list:club.missing.join(', ')})}</p>`);
h+=pRow({l:tr('meet_a_network.reach_without_transit'),v:Math.min(R.reachNT,0.999),max:0.999,txt:`${reachPct(R.reachNT)} / 99.9%`});
if(lost.length)h+=`<div class="btns">${lost.slice(0,3).map(nb).join('')}${btn(trn('meet_a_network.all_n_out_of_reach',lost.length),'netFilter',{f:'out'},'pink sm')}</div>`;
return h+'</div>';}

View file

@ -0,0 +1,34 @@
/* ---------- customers overview (#13, #14, #15) ---------- */
const bizMo=b=>{const T=BIZ_T[b.type];return T.event?0:T.fiber?b.rate:b.bw*b.rate;};
// Why a customer is unhappy, in the same terms the daily mood update uses.
function bizWhy(b){const T=BIZ_T[b.type],out=[];if(T.event&&!eventLive(b))return out;
const sf=bizSf(b);if(sf<0.95)out.push(T.fiber?tr('customers.their_fiber_is_down'):tr('customers.getting_only_p_of_the_bandwidth',{p:pct(sf)}));
if(!(T.l2||T.fiber)&&R.reach<=0.99&&!scnRule('local'))out.push(tr('customers.you_cannot_reach_the_whole_internet',{p:pct(R.reach)}));
if(b.type==='scrub'&&!hasScrub())out.push(tr('common.needs_a_scrubbing_center'));
{const q=b.type==='scrub'&&scrubFar(b.city);if(q)out.push(tr('customers.attacks_on_city_are_hauled_to',{city:CITY[b.city].name,to:CITY[q.to].name,ms:Math.round(q.ms)}));}
for(const k of b.reqs||[])if(REQS[k]&&!REQS[k].ok(b))out.push(typeof REQS[k].l==='function'?REQS[k].l(b):REQS[k].l);
return out;}
const moodCls=m=>m<30?'bad':m<60?'warn':'';
const custStats=()=>{const bz=S.biz.filter(b=>!BIZ_T[b.type].event),mo=bz.reduce((a,b)=>a+bizMo(b),0);
return {n:bz.length,unhappy:bz.filter(b=>b.mood<60).length,furious:bz.filter(b=>b.mood<30).length,avg:bz.length?(mo>0?bz.reduce((a,b)=>a+b.mood*bizMo(b),0)/mo:bz.reduce((a,b)=>a+b.mood,0)/bz.length):100,risk:bz.filter(b=>b.mood<60).reduce((a,b)=>a+bizMo(b),0)};};
// Long lists show their first rows and grow on request: a thousand rows of buttons take the browser a long time to
// lay out again every day, worst of all on a phone. Filters, sorting and totals still cover every row.
const LIST_PAGE=100,listN=k=>(UI.listN&&UI.listN[k])||LIST_PAGE,listReset=k=>{if(UI.listN)delete UI.listN[k];};
const listMore=(k,n,lab)=>n>listN(k)?`<div class="btns" style="margin-top:6px">${btn(lab(Math.min(LIST_PAGE,n-listN(k))),'listMore',{k},'ghost sm')}</div>`:'';
function custSection(){const F=UI.kf||{};let h=`<div class="panel2" id="custSec" style="margin-top:12px"><h3>${tr('common.customers')}</h3>`;
if(!S.biz.length)return h+`<p class="empty">${tr('customers.no_customers_yet_offers_show_up')}</p></div>`;
const st=custStats();
h+=`<p class="note" style="margin-top:0">${tr('customers.everyone_who_pays_you_happiest_last')}</p>`;
h+=`<div class="dgrid" style="margin:0 0 8px"><div class="tile"><div class="lbl">${tr('common.happiness')}</div><div class="val" style="color:${st.avg<60?'var(--bad)':'inherit'}">${Math.round(st.avg)}%</div><div class="sub">${tr('customers.weighted_by_what_they_pay')}</div></div><div class="tile"><div class="lbl">${tr('common.unhappy')}</div><div class="val" style="color:${st.unhappy?'var(--bad)':'inherit'}">${st.unhappy}</div><div class="sub">${trn('customers.n_furious',st.furious)}</div></div><div class="tile"><div class="lbl">${tr('common.at_risk')}</div><div class="val">${tr('common.price_mo',{price:fmt$(st.risk)})}</div><div class="sub">${tr('customers.from_unhappy_customers')}</div></div></div>`;
const cities=[...new Set(S.biz.map(b=>b.city))].sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name));
h+=`<div class="trsel" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin-bottom:6px"><div class="seg">${btn(tr('dashboard.all_n',{n:S.biz.length}),'custF',{v:''},!F.f?'pink sm':'ghost sm')}${btn(tr('customers.unhappy_n',{n:S.biz.filter(b=>b.mood<60).length}),'custF',{v:'sad'},F.f==='sad'?'pink sm':'ghost sm')}</div><label>${tr('common.city_906b')} <select data-chg="custCity"><option value="">${tr('common.all_cities')}</option>${cities.map(c=>`<option value="${c}"${F.city===c?' selected':''}>${esc(CITY[c].name)}</option>`).join('')}</select></label></div>`;
const rows=S.biz.filter(b=>(!F.f||b.mood<60)&&(!F.city||b.city===F.city||b.city2===F.city||(b.sites||[]).includes(F.city)));
const sk=UI.custSort||'mood',dir=UI.custDir||1,val=b=>sk==='name'?b.name.toLowerCase():sk==='city'?CITY[b.city].name:sk==='mo'?bizMo(b):b.mood;
rows.sort((a,b)=>{const A=val(a),B=val(b);return (A<B?-1:A>B?1:0)*dir||a.mood-b.mood;});
if(!rows.length)return h+`<p class="empty">${F.f?tr('customers.nobody_is_unhappy_enjoy_it_while'):tr('customers.no_customers_here')}</p></div>`;
const where=b=>b.sites?b.sites.map(c=>CITY[c].name).join(', '):b.city2?`${CITY[b.city].name} ⇄ ${CITY[b.city2].name}`:CITY[b.city].name;
const trend=b=>b.pm===undefined||Math.abs(b.mood-b.pm)<0.05?'':b.mood>b.pm?' <span style="color:var(--eye)">▲</span>':' <span style="color:var(--bad)">▼</span>';
const sorts=[['mood',tr('common.happiness')],['mo',tr('common.per_month')],['name',tr('common.name')],['city',tr('common.where')]];
h+=`<div class="seg" style="margin-bottom:4px">${sorts.map(([k,l])=>btn(l+(sk===k?(dir>0?' ▲':' ▼'):''),'custSort',{k},sk===k?'pink sm':'ghost sm')).join('')}</div>`;
h+=rows.slice(0,listN('cust')).map(b=>{const why=bizWhy(b),grace=S.day-(b.since||0)<15;return `<div class="row"><div class="grow"><div class="nm">${esc(b.name)} <span class="meta">${esc(BIZ_T[b.type].l)}</span></div><div class="meta">${esc(where(b))} · ${BIZ_T[b.type].event?esc(bTerms(b)):tr('common.price_mo',{price:fmt$(bizMo(b))})}${grace?` · ${tr('common.provisioning_n_d_grace',{n:15-(S.day-(b.since||0))})}`:''}</div>${bRisk(b)}${why.length?`<div class="why">${why.map(esc).join(' · ')}</div>`:''}<div class="bar ${moodCls(b.mood)}"><i style="width:${b.mood}%"></i></div><div class="meta">${tr('common.happiness_p',{p:Math.round(b.mood)})}${trend(b)}</div></div>${btn(tr('common.open'),'custGo',{id:b.id},'ghost sm')}</div>`;}).join('');
return h+listMore('cust',rows.length,n=>trn('customers.n_more_customer',n))+`</div>`;}

View file

@ -0,0 +1,65 @@
/* ---------- connections overview (#31, #33, #38) ----------
Every transit port, PNI, IX port, cache and fabric port in one list, filterable by type, city and
network, with a jump to the POP that holds it. The Networks tab shows the same per network. */
const CONN_K={t:N_('common.transit'),p:'PNI',ix:'IX',c:N_('common.cache'),nni:'NNI'},CONN_ORD=['t','p','ix','c','nni'],CONN_COL={t:'#FF8A3D',p:'#7B61FF',ix:'#2DB7F5',c:'#16A866',nni:'#1E2640'};
const connTab=k=>k==='t'?'up':k==='nni'?'links':'peer';
function conns(){const out=[],pn=(tier,n)=>(n||1)>1?`${n}×${PORT[tier].n} LAG`:PORT[tier].n;
for(const t of S.transit){const q=(R.p95&&R.p95[t.id])||0;out.push({k:'t',id:t.id,city:t.city,net:t.net,name:NET[t.net].name,port:pn(t.tier,t.n),cap:lagCap(PORT[t.tier].g,t.n),use:R.useT[t.id]||0,mo:transitMo(t,q),down:t.down>S.day||!popUp(t.city),low:t.pref==='low',note:tr('connections.95th_percentile_g',{g:fmtG(q)})});}
for(const x of S.pni){const u=R.usePni[x.id]||0;out.push({k:'p',id:x.id,city:x.city,net:x.net,name:NET[x.net].name,port:x.g1?((x.n||1)>1?x.n+'×1G':'1G'):pn(x.tier,x.n),cap:lagCap(pniG(x),x.n),use:u,mo:pniMo(x,u),down:!popUp(x.city)||!pniOn(x),low:x.pref==='low',note:!pniOn(x)?tr('connections.on_order_n_days',{n:x.ready-S.day}):NET[x.net].pol==='paid'?tr('common.paid_peering'):''});}
for(const c in S.ixp){const ses=ixSessions(c),mine=!!S.myIx[c];out.push({k:'ix',id:c,city:ixCity(c),net:null,nets:[...ses],name:ixName(c),port:mine?tr('common.your_exchange'):pn(S.ixp[c],(S.ixn||{})[c]),cap:ixCap(c),use:R.useIx[c]||0,mo:ixMo(c),mine,down:!!(S.ev.ixdown&&S.ev.ixdown[c]>S.day),low:(S.ixPref&&S.ixPref[c])==='low',note:trn('connections.n_peering_session',ses.size)+(isRemote(c)?' · '+tr('common.remote'):'')});}
const cg={};for(const x of S.caches){const key=x.city+'|'+x.net;(cg[key]=cg[key]||[]).push(x);}
for(const key in cg){const g=cg[key],x=g[0];out.push({k:'c',id:x.id,n:g.length,city:x.city,net:x.net,name:NET[x.net].cache.name,port:trn('common.n_box',g.length),cap:CACHE_CAP*g.length,use:g.reduce((a,y)=>a+(R.useCache[y.id]||0),0),mo:CACHE_MO*g.length,down:!popUp(x.city),low:false,note:tr('common.from_net',{net:NET[x.net].name})});}
for(const x of S.nni||[])if(FAB[x.prov]&&NNI[x.tier])out.push({k:'nni',id:x.city+'|'+x.prov,city:x.city,net:null,name:FAB[x.prov].name,port:NNI[x.tier].n,cap:NNI[x.tier].g,use:nniUsed(x.city,x.prov),mo:NNI[x.tier].mo,down:!popUp(x.city),low:false,note:tr('connections.virtual_circuits_and_fabric')});
return out;}
// Cancel straight from the list, with the same "Really?" step as the POP panel.
// Grow a connection from the list: the next port size and one more LAG member, same actions and prices as the POP panel.
function connUp(r){if(r.mine)return '';const nx=t=>PORT[t+1]&&portShown(t+1)?t+1:-1;let h='';
if(r.k==='t'){const t=S.transit.find(x=>x.id===r.id);if(!t)return '';const n=t.n||1,i=nx(t.tier);
if(i>=0){const a={port:PORT[i].n,cost:fmt$(PORT[i].setup*n),mo:fmt$(PORT[i].tmo*n)};h+=btn(n>1?tr('common.upgrade_all_to_port_cost_mo',a):tr('common.upgrade_port_cost_mo_mo',a),'buyTransit',{city:t.city,net:t.net,tier:i},'sm',S.cash<PORT[i].setup*n||!portOk(t.city,i));}
if(n<LAG_MAX)h+=btn(tr('common.lag_member_cost_mo_mo',{cost:fmt$(PORT[t.tier].setup),mo:fmt$(PORT[t.tier].tmo)}),'lagT',{id:t.id,d:1},'sm',S.cash<PORT[t.tier].setup||!portOk(t.city,t.tier));}
else if(r.k==='p'){const p=S.pni.find(x=>x.id===r.id);if(!p)return '';if(!pniOn(p)||p.up||msfNope(p.net,p.city))return `<span class="meta">${!pniOn(p)||p.up?tr('common.on_order'):''}</span>`;const n=p.n||1,i=p.g1?0:nx(p.tier),c=i>=0?(1500+PORT[i].setup/2)*n:0;
if(i>=0){const a={port:PORT[i].n,cost:fmt$(c),mo:fmt$(PORT[i].pni*n)};h+=btn(n>1?tr('common.upgrade_all_to_port_cost_mo',a):tr('common.upgrade_port_cost_mo_mo',a),'pni',{city:p.city,net:p.net,tier:i},'sm',!portOk(p.city,i)||S.cash<c);}
if(n<LAG_MAX)h+=btn(tr('common.lag_member_cost_mo_mo',{cost:fmt$(1500+PORT[p.tier].setup/2),mo:fmt$(PORT[p.tier].pni)}),'lagP',{id:p.id,d:1},'sm',S.cash<1500+PORT[p.tier].setup/2);}
else if(r.k==='ix'){const c=r.id,city=ixCity(c),n=(S.ixn||{})[c]||1,i=nx(S.ixp[c]);
if(i>=0)h+=btn(tr('common.upgrade_port_price',{port:PORT[i].n,price:portMo(ixPortMo(c,i)*n)}),'buyIx',{city:c,tier:i},'sm',(!!S.pops[city]&&!portOk(city,i))||(!S.pops[city]&&i>1));
if(S.pops[city]&&!S.myIx[c]&&n<LAG_MAX)h+=btn(tr('common.lag_member_price',{price:portMo(ixPortMo(c,S.ixp[c]))}),'lagIx',{city:c,d:1},'sm',S.cash<ixPortMo(c,S.ixp[c]));}
else if(r.k==='c')h+=btn(tr('common.box'),'cache',{city:r.city,net:r.net},'sm');
else if(r.k==='nni'){const [city,prov]=r.id.split('|'),pt=nniPort(city,prov);if(pt&&pt.tier<NNI.length-1)h+=btn(tr('common.upgrade_port_price_mo',{port:NNI[pt.tier+1].n,price:fmt$(NNI[pt.tier+1].mo)}),'buyNni',{city,prov,tier:pt.tier+1},'sm');}
return h;}
function connX(r){if(r.mine)return '';const on=UI.confirm==='cc:'+r.k+':'+r.id;
return btn(on?(r.k==='ix'?tr('common.really_leave'):r.k==='t'?tr('common.really_cancel'):tr('common.really_remove')):r.k==='ix'?tr('common.leave_ix'):r.k==='t'?tr('common.cancel'):r.k==='c'&&r.n>1?tr('common.box_6ee3'):r.k==='nni'?tr('common.remove_port'):tr('common.remove'),'connCancel',{k:r.k,id:r.id},on?'red sm':'ghost sm');}
function connMatch(r,F){return (!F.k||r.k===F.k)&&(!F.city||r.city===F.city)&&(!F.net||r.net===F.net||(r.nets&&r.nets.includes(F.net)));}
function connSection(){const all=conns(),F=UI.cf||{};
let h=`<div class="panel2" id="connSec" style="margin-top:12px"><h3>${tr('common.connections')}</h3><p class="note" style="margin-top:0">${tr('connections.every_port_that_connects_you_to')}</p>`;
if(!all.length)return h+`<p class="empty">${tr('connections.no_connections_yet_buy_transit_or')}</p></div>`;
const cnt=k=>all.filter(r=>r.k===k&&connMatch(r,{...F,k:null})).length;
h+=`<div class="seg" style="margin-bottom:6px">${btn(tr('dashboard.all_n',{n:all.filter(r=>connMatch(r,{...F,k:null})).length}),'connF',{f:'k',v:''},!F.k?'pink sm':'ghost sm')}${CONN_ORD.filter(k=>all.some(r=>r.k===k)).map(k=>btn(`${tr(CONN_K[k])} (${cnt(k)})`,'connF',{f:'k',v:k},F.k===k?'pink sm':'ghost sm')).join('')}</div>`;
const cities=[...new Set(all.map(r=>r.city))].sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name));
const nets=[...new Set(all.flatMap(r=>r.net?[r.net]:(r.nets||[])))].filter(id=>NET[id]&&!NET[id].tail).sort((a,b)=>NET[a].name.localeCompare(NET[b].name));
h+=`<div class="trsel" style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:6px"><label>${tr('common.city_906b')} <select data-chg="connCity"><option value="">${tr('common.all_cities')}</option>${cities.map(c=>`<option value="${c}"${F.city===c?' selected':''}>${esc(CITY[c].name)}</option>`).join('')}</select></label><label>${tr('common.network_6974')} <select data-chg="connNet"><option value="">${tr('common.all_networks')}</option>${nets.map(id=>`<option value="${id}"${F.net===id?' selected':''}>${esc(NET[id].name)}</option>`).join('')}</select></label>${F.k||F.city||F.net?btn(tr('common.clear_filters'),'connF',{f:'all',v:''},'ghost sm'):''}</div>`;
const rows=all.filter(r=>connMatch(r,F));
const sk=UI.connSort||'k',dir=UI.connDir||1,val=r=>sk==='city'?CITY[r.city].name:sk==='name'?r.name.toLowerCase():sk==='use'?(r.cap?r.use/r.cap:0):sk==='mo'?r.mo:CONN_ORD.indexOf(r.k);
rows.sort((a,b)=>{const A=val(a),B=val(b);return (A<B?-1:A>B?1:0)*dir||CONN_ORD.indexOf(a.k)-CONN_ORD.indexOf(b.k)||CITY[a.city].name.localeCompare(CITY[b.city].name)||a.name.localeCompare(b.name);});
const tc=rows.reduce((a,r)=>a+r.cap,0),tu=rows.reduce((a,r)=>a+r.use,0),tm=rows.reduce((a,r)=>a+r.mo,0);
if(isPhone()){const st=(r)=>r.down?` <span class="tag restrictive">${tr('common.down')}</span>`:r.low?` <span class="tag st">${tr('common.backup')}</span>`:'';
h+=`<div class="seg" style="margin-bottom:4px">${[['k',tr('common.type')],['city',tr('common.where')],['use',tr('common.in_use')],['mo',tr('common.per_month')]].map(([k,l])=>btn(l+(sk===k?(dir>0?' ▲':' ▼'):''),'connSort',{k},sk===k?'pink sm':'ghost sm')).join('')}</div>`;
h+=rows.slice(0,listN('conn')).map(r=>{const u=r.cap?r.use/r.cap:0,N=r.net&&NET[r.net];return `<div class="row"${r.down?' style="opacity:.55"':''}>${N?logo(N):`<span class="logo" style="--c:${CONN_COL[r.k]}">${r.k==='nni'?'NNI':'IX'}</span>`}<div class="grow"><div class="nm">${esc(r.name)} <span class="tag" style="background:${CONN_COL[r.k]}">${tr(CONN_K[r.k])}</span>${st(r)}</div><div class="meta">${esc(CITY[r.city].name)} · ${esc(r.port)} · ${tr('common.price_mo',{price:fmt$(r.mo)})}${r.note?' · '+esc(r.note):''}</div><div class="kv"><span>${tr('common.in_use')}</span><b>${fmtG(r.use)} / ${fmtCap(Math.round(r.cap))}</b></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div>${r.mine?'':`<div class="btns">${connUp(r)}${connX(r)}</div>`}</div>${btn(tr('common.open'),'goConn',{city:r.city,k:r.k},'ghost sm')}</div>`;}).join('');
return h+listMore('conn',rows.length,n=>trn('connections.n_more_connection',n))+`<div class="kv" style="margin-top:6px"><span><b>${trn('connections.n_connection',rows.length)}</b></span><b>${fmtG(tu)} / ${fmtCap(Math.round(tc))} · ${tr('common.price_mo',{price:fmt$(tm)})}</b></div></div>`;}
const th=(k,l,c)=>`<th class="${c||''}">${k?`<button class="thb" data-act="connSort" data-args="${esc(JSON.stringify({k}))}">${l}${sk===k?(dir>0?' ▲':' ▼'):''}</button>`:l}</th>`;
h+=`<div class="tscroll"><table class="tbl"><thead><tr>${th('k',tr('common.type'))}${th('city',tr('common.where'))}${th('name',tr('common.with'))}${th('',tr('common.port'))}${th('use',tr('common.in_use'),'r')}${th('mo',tr('common.per_month'),'r')}<th></th></tr></thead><tbody>`;
h+=rows.slice(0,listN('conn')).map(r=>{const u=r.cap?r.use/r.cap:0,N=r.net&&NET[r.net];return `<tr${r.down?' style="opacity:.55"':''}><td><span class="tag" style="background:${CONN_COL[r.k]}">${tr(CONN_K[r.k])}</span></td><td>${esc(CITY[r.city].name)}</td><td><span style="display:inline-flex;align-items:center;gap:6px">${N?logo(N):''}<span><b>${esc(r.name)}</b>${r.note?`<br><span class="meta">${esc(r.note)}</span>`:''}</span></span></td><td>${esc(r.port)}${r.down?` <span class="tag restrictive">${tr('common.down')}</span>`:r.low?` <span class="tag st">${tr('common.backup')}</span>`:''}</td><td class="r">${fmtG(r.use)} / ${fmtCap(Math.round(r.cap))}<div class="bar ${barCls(u)}" style="margin-top:3px"><i style="width:${Math.min(100,u*100)}%"></i></div></td><td class="r">${fmt$(r.mo)}</td><td><div style="display:flex;flex-wrap:wrap;gap:6px;min-width:220px">${btn(tr('common.open'),'goConn',{city:r.city,k:r.k},'ghost sm')}${connUp(r)}${connX(r)}</div></td></tr>`;}).join('');
h+=`</tbody><tfoot><tr><td colspan="4"><b>${trn('connections.n_connection',rows.length)}</b></td><td class="r"><b>${fmtG(tu)} / ${fmtCap(Math.round(tc))}</b></td><td class="r"><b>${fmt$(tm)}</b></td><td></td></tr></tfoot></table></div>${listMore('conn',rows.length,n=>trn('connections.n_more_connection',n))}</div>`;
return h;}
// Where you connect to one network, as buttons that jump to the POP (Networks tab).
// Where you connect to each network, as [label, city, kind]: transit, PNIs, IX sessions, then caches. Built for all
// networks at once, so the network list works out each IX port's sessions a single time, not once per network.
function netWhereIdx(){const B={t:{},p:{},ix:{},c:{}},add=(k,id,x)=>(B[k][id]||(B[k][id]=[])).push(x);
for(const t of S.transit)add('t',t.net,[tr('common.transit'),t.city,'t']);
for(const x of S.pni)add('p',x.net,['PNI',x.city,'p']);
for(const c in S.ixp){const nm=ixName(c),ct=ixCity(c);for(const id of ixSessions(c))add('ix',id,[nm,ct,'ix']);}
const seen=new Set();for(const x of S.caches){const k=x.net+'|'+x.city;if(!seen.has(k)){seen.add(k);add('c',x.net,[tr('common.cache'),x.city,'c']);}}
return id=>[].concat(B.t[id]||[],B.p[id]||[],B.ix[id]||[],B.c[id]||[]);}
function netWhere(n,where){const ch=(where||netWhereIdx())(n.id);
if(!ch.length)return '';const MAX=6;
return `<div class="btns">${ch.slice(0,MAX).map(([l,c,k])=>btn(`${esc(l)} <small>${esc(CITY[c].name)}</small>`,'goConn',{city:c,k},'ghost sm')).join('')}${ch.length>MAX?btn(tr('dashboard.n_more',{n:ch.length-MAX}),'connFor',{net:n.id},'ghost sm'):''}</div>`;}
const DTABS=['overview','cust','conn','traffic','infra','lease'];

View file

@ -0,0 +1,37 @@
/* Leased lines you could swap for your own glass: waves, fabric circuits and IRUs between two of your POPs,
priced against digging (land) or laying a cable (subsea), with enough optics to match what you lease today. */
function swapOptics(km,cap,sub,sys){for(let r=0;r<=(sub?0:REGEN_MAX);r++){const l={km,regen:r,sub};let b=null;
for(const o in OPT){if(OPT[o].lvl>lvl()||sys==='lite'&&OPT[o].sys==='roadm')continue;const g=optG(o,l),c=optCost(o);if(g&&(!b||c/g<b.c/b.g))b={g,c};}
if(b){const n=Math.ceil(cap/b.g);return {n,r,up:Math.round(n*b.c*(1+REGEN_CH*r))+r*REGEN_COST,mo:r*REGEN_MO};}}return null;}
const leaseCap=ls=>ls.reduce((s,l)=>s+(l.kind==='vxc'?VXC[l.vt].g:l.kind==='df'?(l.ch||[]).reduce((t,o)=>t+optG(o,l),0):LT[l.tier].g),0);
const swapOpt=(k,up,omo,days,mo)=>{const save=mo-omo;return {k,up,omo,days,save,pay:save>0?Math.ceil(up/save):0};};
// Lighting leased capacity on a fiber you already have (#72 review): needs free channels, and optics cost money.
function litOn(L,cap){const free=chMax(L)-(L.ch||[]).length-soldSlots(L);let b=null;
for(const o in OPT){const O=OPT[o];if(O.lvl>lvl()||(O.sys==='roadm'&&!isRdm(L.sys))||[L.a,L.b].some(c=>S.pops[c]&&RG[S.pops[c].rgen||0].cls<O.rg))continue;const g=optG(o,L),c=chCost(L,o);if(g&&(!b||c/g<b.c/b.g))b={o,g,c};}
if(!b)return {free,n:0,fits:false};const n=Math.ceil(cap/b.g);return {free,n,up:n*b.c,fits:n<=free};}
function leaseSwaps(){const by={};
for(const l of S.links){if(l.kind==='df'&&l.own||!S.pops[l.a]||!S.pops[l.b])continue;const k=[l.a,l.b].sort().join('|');(by[k]=by[k]||[]).push(l);}
return Object.entries(by).map(([k,ls])=>{const [a,b]=k.split('|'),sub=isSub(a,b),mo=ls.reduce((s,l)=>s+(l.mo||0),0),cap=leaseCap(ls);
const x={a,b,sub,ls,mo,cap,opts:[],own:pairLinks(a,b).find(l=>l.kind==='df'&&l.own&&l.ready<=S.day)};if(x.own){x.fit=litOn(x.own,cap);if(x.fit.fits)x.best=mo;return x;}
// Waves and fabric circuits can also move onto a leased fiber pair: cheaper glass, but you buy the gear.
const ws=ls.filter(l=>l.kind!=='df'),wmo=ws.reduce((s,l)=>s+(l.mo||0),0),sc=sub?subDfCable(a,b):null;x.iru=ls.find(l=>l.kind==='df');
if(ws.length&&x.iru){x.fit=litOn(x.iru,leaseCap(ws));if(x.fit.fits)x.lit=wmo;}
else if(ws.length&&lvl()>=2&&(sub?sc:dfAllowed(a,b))){const km=sc?sc.km:kmBetween(a,b),sys=lvl()>=3?'roadm':'lite',wc=leaseCap(ws),op=swapOptics(km,wc,sub,sys);
if(op&&op.n<=DF_SYS[sys].max)x.opts.push(swapOpt('iru',DF_SYS[sys].cost+ampCount(km)*AMP_COST+op.up,dfLeaseMo(km)+ampCount(km)*AMP_MO+op.mo,30,wmo));}
// Dig on land, lay a cable between landing stations (even ones that share a landmass), or both.
const whys=[];for(const cab of [false,true]){if(cab?!seaCab(a,b):sub)continue;
const why=cab?ownCabWhy(a,b):!dfAllowed(a,b)?tr('lease_swaps.nobody_lets_you_dig_on_this'):lvl()<3?tr('lease_swaps.digging_your_own_fiber_unlocks_at'):'';
if(why){whys.push(why);continue;}const km=cab?ownCabKm(a,b):kmBetween(a,b),op=swapOptics(km,cap,cab,'roadm');
if(!op){whys.push(tr('lease_swaps.no_optic_you_can_buy_reaches',{km:km.toLocaleString()}));continue;}
x.opts.push(swapOpt(cab?'cab':'own',(cab?ownCabCost(km):dfBuildCost(km)+DF_SYS.roadm.cost+ampCount(km)*AMP_COST)+op.up,(cab?ownCabMo(km):Math.round(km*0.15)+ampCount(km)*AMP_MO)+op.mo,cab?ownCabDays(km):dfBuildDays(km),mo));}
x.why=x.opts.some(o=>o.k!=='iru')?'':whys.join(' ');
const sv=[...x.opts.map(o=>o.save),x.lit].filter(v=>v!==undefined);if(sv.length)x.best=Math.max(...sv);return x;})
.sort((p,q)=>((p.best===undefined)-(q.best===undefined))||(q.best||0)-(p.best||0)||q.mo-p.mo);}
function leaseTab(){const xs=leaseSwaps(),tot=xs.reduce((s,x)=>s+x.mo,0);
const kind=l=>l.kind==='vxc'?tr('lease_swaps.cap_fabric_circuit',{cap:capName(l)}):l.kind==='df'?tr('lease_swaps.cap_on_a_dark_fiber_iru',{cap:capName(l)}):tr('lease_swaps.cap_wave',{cap:capName(l)});
const line=(x,o)=>{const a={up:fmt$(o.up),mo:fmt$(o.omo),n:o.days};return `<div class="meta">${o.k==='iru'?tr('lease_swaps.lease_dark_fiber_up_up_front',a):o.k==='cab'?tr('lease_swaps.your_own_cable_up_up_front',a):tr('lease_swaps.your_own_fiber_up_up_front',a)} <b style="color:${o.save>0?'var(--eye)':'var(--bad)'}">${o.save>0?tr('lease_swaps.saves_price_mo_pays_for_itself',{price:fmt$(o.save),n:o.pay}):tr('lease_swaps.costs_more_than_leasing_at_this')}</b></div>`;};
const plan=(x,o)=>btn(o.k==='iru'?tr('lease_swaps.plan_dark_fiber'):o.k==='cab'?tr('lease_swaps.plan_a_cable'):tr('lease_swaps.plan_your_own_fiber'),'leaseSwap',{a:x.a,b:x.b,src:o.k==='iru'?'lease':o.k==='cab'?'cable':'build'},o.save>0&&o.save===x.best?'pink sm':'ghost sm');
return `<div class="panel2" style="margin-top:12px"><h3>${tr('common.leased_lines')}</h3><p class="note" style="margin-top:0">${tr('lease_swaps.every_wave_fabric_circuit_and_dark')}</p>
${xs.length?`<div class="kv"><span>${tr('lease_swaps.you_pay_for_leases')}</span><b>${tr('common.price_mo',{price:fmt$(tot)})}</b></div>`+xs.map(x=>`<div class="row"><div class="grow"><div class="nm">${CITY[x.a].name} ⇄ ${CITY[x.b].name} <span class="tag st">${x.sub?tr('common.subsea'):tr('common.land')}</span></div><div class="meta">${Object.entries(x.ls.reduce((m,l)=>(m[kind(l)]=(m[kind(l)]||0)+1,m),{})).map(([k,n])=>n>1?`${n} × ${k}`:k).join(', ')} · ${tr('common.price_mo',{price:fmt$(x.mo)})}</div>
${x.fit&&x.fit.fits?`<div class="meta">${x.own?tr('lease_swaps.you_already_own_fiber_here_light',{n:x.fit.n,up:fmt$(x.fit.up),price:fmt$(x.best)}):tr('lease_swaps.you_already_lease_dark_fiber_here',{n:x.fit.n,up:fmt$(x.fit.up),price:fmt$(x.lit)})}</div>`:x.fit?`<div class="meta">${x.fit.n?tr('lease_swaps.your_fiber_here_has_room_for',{free:Math.max(0,x.fit.free),n:x.fit.n}):tr('lease_swaps.no_optic_you_can_buy_works')}</div>`:''}${x.opts.map(o=>line(x,o)).join('')}${!x.own&&x.why?`<div class="meta">${esc(x.why)}</div>`:''}
<div class="btns">${x.own?btn(tr('lease_swaps.open_your_fiber'),'dashLink',{id:x.own.id},'pink sm'):''}${x.iru&&x.fit?btn(tr('lease_swaps.open_your_dark_fiber'),'dashLink',{id:x.iru.id},x.lit!==undefined?'pink sm':'ghost sm'):''}${x.opts.map(o=>plan(x,o)).join('')}${btn(tr('common.open_lease'),'dashLink',{id:(x.ls.find(l=>l.kind!=='df')||x.ls[0]).id},'ghost sm')}</div></div></div>`).join(''):`<p class="empty">${tr('lease_swaps.you_do_not_lease_any_lines')}</p>`}</div>`;}

View file

@ -0,0 +1,31 @@
function dashTabs(){const u=custStats().unhappy,cur=UI.dtab||'overview',L={overview:tr('common.overview'),cust:tr('common.customers'),conn:tr('common.connections'),traffic:tr('common.traffic'),infra:tr('common.links_routers'),lease:tr('common.leased_lines')};
return `<nav class="dtabs">${DTABS.map(k=>`<button class="${cur===k?'on':''}" data-act="dashTab" data-args='{"k":"${k}"}'>${L[k]}${k==='cust'&&u?`<span class="cnt red">${u}</span>`:''}</button>`).join('')}</nav>`;}
function renderDash(){checkLayer();
const H=S.hist||[],rows=H.slice(-90),last30=H.slice(-30);
const up=last30.length?last30.reduce((a,r)=>a+(r.dem?Math.min(1,r.srv/r.dem):1),0)/last30.length:1;
const net=R.revMo-R.costMo,tot=Object.values(R.egT).reduce((a,b)=>a+b,0)||1;
const tile=(l,v,sub)=>`<div class="tile"><div class="lbl">${l}</div><div class="val">${v}</div>${sub?`<div class="sub">${sub}</div>`:''}</div>`;
let h=`<div style="display:flex;align-items:center;gap:10px"><div><div class="eyebrow">AS${S.asn} · ${esc(S.name)} · ${tierLabel()}</div><h2 style="font-size:28px">${tr('common.noc_dashboard')}</h2></div><button class="x" data-act="dashClose" aria-label="${tr('common.close')}">×</button></div>`+dashTabs();const DT=UI.dtab||'overview';if(DT==='overview')h+=`
<div class="dgrid">${tile(tr('common.traffic_now'),fmtG(R.served),tr('dashboard.of_g_wanted',{g:fmtG(R.demand)}))}${tile(tr('common.peak'),fmtG(S.stats.peak))}${tile(tr('dashboard.delivered_30_days'),(up*100).toFixed(1)+'%',up>=0.999?tr('dashboard.five_nines_ish'):up>=0.99?tr('dashboard.two_nines_and_change'):tr('dashboard.customers_are_upset'))}${tile(tr('common.peering_ratio'),pct(R.peerShare||0),tr('dashboard.caches_pnis_and_ix'))}${tile(tr('dashboard.monthly_p_l'),`<span style="color:${net>=0?'var(--eye)':'var(--bad)'}">${net>=0?'+':''}${fmt$(net)}</span>`,tr('dashboard.in_in_out_out',{in:fmt$(R.revMo),out:fmt$(R.costMo)}))}${tile(tr('common.incidents'),S.stats.incidents,tr('dashboard.n_shrugged_off',{n:S.stats.survived}))}</div>
<div class="dcols"><div class="panel2"><h3>${tr('dashboard.traffic_by_way_out')}</h3>${svgChart(rows,['c','p','ix','t','l2'],[{k:'dem',col:'#1E2640',dash:true}],v=>fmtCap(Math.round(v)))}<div class="legend">${Object.keys(EGC).map(k=>`<span><i style="background:${EGC[k][1]}"></i>${EGC[k][0]} ${pct((R.egT[k]||0)/tot)}</span>`).join('')}<span><i style="background:#fff;border-style:dashed"></i>${tr('common.demand')}</span></div></div>
<div class="panel2"><h3>${tr('dashboard.money_per_month')}</h3>${svgChart(rows,[],[{k:'rev',col:'#16A866'},{k:'cost',col:'#FF4D5E'}],v=>fmt$(v))}<div class="legend"><span><i style="background:#16A866"></i>${tr('common.revenue')}</span><span><i style="background:#FF4D5E"></i>${tr('common.costs')}</span></div>
<h3 style="margin-top:8px">${tr('dashboard.where_the_money_goes')}</h3>${Object.entries(R.cost).filter(([k,v])=>v>0).sort((a,b)=>b[1]-a[1]).map(([k,v])=>`<div class="kv"><span>${{pops:tr('dashboard.pops_and_routers'),links:tr('dashboard.waves_and_fiber'),transit:tr('common.transit'),ix:tr('common.ix_ports'),pni:tr('common.pnis'),caches:tr('common.cache_power'),nni:tr('common.fabric_ports'),optical:tr('dashboard.amp_huts_and_spares'),loans:tr('common.loan_repayments'),revshare:tr('dashboard.investor_revenue_share'),extras:tr('dashboard.licenses_and_scrubbing'),wholesale:tr('dashboard.nearly_broadband_network_wholesale'),levy:tr('dashboard.regional_broadband_levy')}[k]||k}</span><b>${tr('common.price_mo',{price:fmt$(v)})}</b></div>`).join('')}</div></div>`;
const tT=(R.egT.t||0)||1;
const row=(n,e,want)=>{const t=e.c+e.p+e.ix+e.t;return {n,e,t,want,cost:(R.cost.transit||0)*e.t/tT,lost:want>0.01?Math.max(0,1-t/want):0};};
const nets=NETS.filter(n=>!n.tail).map(n=>row(n,R.netEg[n.id]||{c:0,p:0,ix:0,t:0},R.demTo[n.id]||0));
{const e={c:0,p:0,ix:0,t:0};let w=0;for(const n of NETS)if(n.tail){const x=R.netEg[n.id];if(x)for(const k in e)e[k]+=x[k]||0;w+=R.demTo[n.id]||0;}nets.push(row({id:'_tail',name:tr('dashboard.the_long_tail_n_small_networks',{n:NETS.filter(n=>n.tail).length}),asn:'many',type:'eye',col:'#8A93B8'},e,w));}
for(let i=nets.length-1;i>=0;i--)if(!(nets[i].t>0.01||nets[i].want>0.01))nets.splice(i,1);
{const k=UI.dashSort||'traffic',dir=UI.dashDir||-1,val=x=>k==='name'?x.n.name.toLowerCase():k==='asn'?x.n.asn:k==='type'?x.n.type:k==='cost'?x.cost:k==='lost'?x.lost:x.t;nets.sort((a,b)=>{const A=val(a),B=val(b);return (A<B?-1:A>B?1:0)*dir||b.t-a.t;});}
if(DT==='cust')h+=custSection();
if(DT==='conn')h+=connSection();
if(DT==='traffic')h+=`<div class="panel2" style="margin-top:12px"><h3>${tr('dashboard.traffic_by_network_asn')}</h3><p class="note" style="margin-top:0">${tr('dashboard.where_your_users_traffic_comes_from')}</p><div class="legend" style="margin:0 0 6px">${['c','p','ix','t'].map(k=>`<span><i style="background:${EGC[k][1]}"></i>${EGC[k][0]}</span>`).join('')}</div><div class="tscroll"><table class="tbl"><thead><tr>${[['name',tr('common.network_6974'),''],['asn','AS',''],['type',tr('common.type'),''],['traffic',tr('common.traffic'),'r'],['mix',tr('dashboard.how_it_arrives'),''],['cost',tr('common.transit_cost'),'r'],['lost',tr('common.lost'),'r']].map(([k,l,c])=>`<th class="${c}">${k==='mix'?l:`<button class="thb" data-act="dashSort" data-args="${esc(JSON.stringify({k}))}">${l}${UI.dashSort===k?(UI.dashDir>0?' ▲':' ▼'):''}</button>`}</th>`).join('')}</tr></thead><tbody>
${nets.map(({n,e,t,want})=>{return `<tr><td><span style="display:inline-flex;align-items:center;gap:6px">${logo(n)}<b>${esc(n.name)}</b></span></td><td>${n.asn}</td><td><span class="tag ${n.type}">${TYPE_L[n.type]}</span></td><td class="r">${fmtG(t)}</td><td><div class="mix" title="${['c','p','ix','t'].filter(k=>e[k]>0.01).map(k=>EGC[k][0]+' '+fmtG(e[k])).join(' · ')||tr('common.nothing_yet')}">${['c','p','ix','t'].map(k=>`<i style="width:${t?e[k]/t*100:0}%;background:${EGC[k][1]}"></i>`).join('')}</div></td><td class="r">${e.t>0.01?tr('common.price_mo',{price:fmt$((R.cost.transit||0)*e.t/tT)}):'—'}</td><td class="r" style="color:${want-t>want*0.05?'var(--bad)':'inherit'}">${want>0.01?pct(Math.max(0,1-t/want)):'—'}</td></tr>`;}).join('')}</tbody></table></div></div>`;
if(DT==='traffic'){const top=transitTop(S.transit.map(t=>t.id),8);if(top.length)h+=`<div class="panel2" style="margin-top:12px"><h3>${tr('dashboard.who_your_transit_carries')}</h3><p class="note" style="margin-top:0">${tr('dashboard.the_networks_you_pay_transit_to')}</p>${top.map(([id,v])=>`<div class="row">${logo(NET[id])}<div class="grow"><div class="nm">${esc(NET[id].name)} <span class="meta">AS${NET[id].asn} · ${fmtG(v)} · ${tr('dashboard.about_price_mo',{price:fmt$((R.cost.transit||0)*v/tT)})}</span></div><div class="meta">${esc(offTransitHint(id))}</div></div>${btn(tr('common.where_6276'),'netFocus',{id},'ghost sm')}</div>`).join('')}</div>`;}
const ls=S.links.filter(l=>capOf(l)>0).map(l=>({l,u:(R.load[l.id]||0)/capOf(l)})).sort((a,b)=>b.u-a.u).slice(0,8);
const rs=Object.keys(S.pops).map(c=>({c,u:(R.nodeLoad[c]||0)/(R.nodeCap[c]||1)})).sort((a,b)=>b.u-a.u).slice(0,6);
if(DT==='infra')h+=`<div class="dcols" style="margin-top:12px"><div class="panel2"><h3>${tr('common.busiest_links')}</h3>${ls.length?ls.map(({l,u})=>`<div class="row"><div class="grow"><div class="nm">${CITY[l.a].name} ⇄ ${CITY[l.b].name} <span class="meta">${capName(l)} · ${linkLat(l).toFixed(1)} ms</span></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div></div><b class="num" style="min-width:42px;text-align:right">${pct(u)}</b>${btn(tr('common.open'),'dashLink',{id:l.id},'ghost sm')}</div>`).join(''):'<p class="empty">'+tr('common.no_links_yet')+'</p>'}</div>
<div class="panel2"><h3>${tr('common.router_load')}</h3>${rs.map(({c,u})=>`<div class="row"><div class="grow"><div class="nm">${CITY[c].name} <span class="meta">${(S.pops[c].routers||1)} × ${esc(RG[S.pops[c].rgen||0].n)}</span></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div></div><b class="num" style="min-width:42px;text-align:right">${pct(u)}</b></div>`).join('')}
<h3 style="margin-top:10px">${tr('common.your_as')}</h3><div class="kv"><span>${tr('common.as_number')}</span><b>AS${S.asn}</b></div><div class="kv"><span>${tr('common.prefixes')}</span><b>${Math.max(1,Math.ceil(Object.keys(S.pops).length/3))} × /22 IPv4, 1 × /32 IPv6</b></div><div class="kv"><span>${tr('common.bgp_sessions')}</span><b>${R.sessions}</b></div><div class="kv"><span>${tr('common.upstreams')}</span><b>${new Set(S.transit.map(t=>t.net)).size}</b></div><div class="kv"><span>${tr('common.reach')}</span><b>${pct(R.reach)}</b></div><div class="kv"><span>${tr('common.customers')}</span><b>${tr('dashboard.n_businesses',{n:S.biz.length})}</b></div></div></div>`;
if(DT==='lease')h+=leaseTab();
if(h!==UI._dh){UI._dh=h;morph($('dashCard'),h);}
}

View file

@ -0,0 +1,30 @@
function loanSummary(o){return o.model==='transit'?tr('bank.you_pay_pct_of_your_transit',{pct:pct(o.cut||0.3),price:fmt$(o.owe||o.amount)}):o.model==='balloon'?tr('bank.nothing_to_pay_for_n_months',{n:o.term}):tr('bank.pay_mo_for_n_months',{pay:fmt$(o.pay),n:o.term})+(o.share?' '+tr('bank.plus_pct_of_your_revenue_until',{pct:pct(o.share)}):'');}
function loanLine(l){const sh=l.share?' · '+tr('bank.plus_pct_of_revenue',{pct:pct(l.share)}):'',fee=loanFees(l)?' · '+tr('bank.price_mo_in_extras',{price:fmt$(loanFees(l))}):'';
if(l.model==='transit')return tr('bank.pct_of_your_transit_bill_n',{pct:pct(l.cut||0.3),n:l.left})+sh+fee;
if(l.model==='balloon')return tr('bank.nothing_to_pay_until_the_end',{n:l.left,apr:(l.apr*100).toFixed(1)})+sh+fee;
return tr('bank.pay_mo_n_months_left_apr',{pay:fmt$(l.pay),n:l.left,apr:(l.apr*100).toFixed(1)})+(l.model==='storm'?' · '+tr('bank.2_per_open_incident'):l.model==='astro'?' · '+tr('bank.rate_set_by_the_stars_each'):'')+sh+fee;}
function renderBank(){
if(!S||$('bankBox').hidden)return;const rt=rating(),net=R.revMo-R.costMo;
const terms=(o)=>{const B=BANKS[o.bank],sh=o.share&&!B.equity?`<span class="tag selective">${tr('bank.plus_pct_of_revenue_until_repaid',{pct:pct(o.share)})}</span>`:'';
if(o.model==='transit')return `<span class="tag st on">${tr('bank.pct_of_your_transit_bill',{pct:pct(o.cut||0.3)})}</span><span class="tag st">${tr('bank.price_to_repay',{price:fmt$(o.owe||o.amount)})}</span><span class="tag st">${tr('bank.n_months',{n:o.term})}</span><span class="tag selective">${tr('bank.the_rest_is_due_at_the')}</span>${sh}`;
if(o.model==='balloon')return `<span class="tag st on">${tr('bank.nothing_to_pay_until_the_end_2a38')}</span><span class="tag st">${tr('bank.apr_apr',{apr:(o.apr*100).toFixed(1)})}</span><span class="tag st">${tr('bank.n_months',{n:o.term})}</span><span class="tag selective">${tr('bank.then_about_price_at_once',{price:fmt$(o.amount*Math.pow(1+o.apr/12,o.term))})}</span>${sh}`;
const extra=o.model==='storm'?`<span class="tag selective">${tr('bank.2_per_open_incident')}</span>`:o.model==='astro'?`<span class="tag selective">${tr('bank.rate_set_by_the_stars_each')}</span>`:'';
return (B.equity?`<span class="tag st on">${tr('common.no_repayments')}</span><span class="tag st">${tr('bank.pct_of_revenue_forever',{pct:pct(o.share)})}</span><span class="tag st">${tr('bank.buy_out_price',{price:fmt$(o.amount*3)})}</span>`:`<span class="tag st on">${tr('bank.apr_apr',{apr:(o.apr*100).toFixed(1)})}</span><span class="tag st">${tr('bank.n_months',{n:o.term})}</span><span class="tag st">${tr('common.price_mo',{price:fmt$(o.pay)})}</span>${B.crypto?'<span class="tag selective">'+tr('bank.paid_in_tubecoin')+'</span>':''}`)+extra+sh;};
const covList=(l)=>l.covs.length?l.covs.map(c=>{const ok=COVS[c].ok(l);return `<div class="meta"><b style="color:${ok?'var(--eye)':'var(--bad)'}">${ok?'✓':'✗'}</b> ${esc(covLabel(c))}</div>`;}).join(''):'<div class="meta">'+tr('bank.no_conditions_that_is_the_scary')+'</div>';
let h=`<div style="display:flex;align-items:center;gap:12px"><div><div class="eyebrow">AS${S.asn} · ${esc(S.name)}</div><h2 style="font-size:28px">${tr('common.bank')}</h2></div><button class="x" data-act="bankClose" aria-label="${tr('common.close')}">×</button></div>
<div class="dgrid"><div class="tile"><div class="lbl">${tr('common.cash')}</div><div class="val" style="color:${S.cash<0?'var(--bad)':'inherit'}">${fmt$(S.cash)}</div><div class="sub">${S.cash<0?tr('bank.bankrupt_at_100k'):tr('bank.in_the_vault')}</div></div>
<div class="tile"><div class="lbl">${tr('dashboard.monthly_p_l')}</div><div class="val" style="color:${net>=0?'var(--eye)':'var(--bad)'}">${net>=0?'+':''}${fmt$(net)}</div><div class="sub">${tr('bank.after_loan_payments')}</div></div>
<div class="tile"><div class="lbl">${tr('common.credit_rating')}</div><div class="val">${rt}</div><div class="sub">${rIdx(rt)>=5?tr('bank.bankers_return_your_calls'):rIdx(rt)>=3?tr('bank.bankers_return_your_emails'):tr('bank.bankers_pretend_to_be_out')}</div></div>
<div class="tile"><div class="lbl">${tr('common.debt')}</div><div class="val">${fmt$(S.loans.reduce((a,l)=>a+(BANKS[l.bank].equity?0:l.bal),0))}</div><div class="sub">${trn('bank.n_loan',S.loans.length)}</div></div></div>`;
h+=`<h3 style="font-size:18px;margin-top:6px">${tr('common.offers')}</h3>`;
if(!S.loanOffers.length)h+=`<p class="empty">${tr('bank.no_offers_right_now_banks_get')}</p>`;
for(const o of S.loanOffers){const B=BANKS[o.bank];h+=`<div class="loan"><span class="logo" style="--c:${B.col}">${initials(B)}</span><div class="grow"><div class="nm">${tr('bank.bank_offers_amount',{bank:esc(B.name),amount:fmt$(o.amount)})}</div><div class="meta">${esc(B.blurb)} · ${tr('bank.offer_ends_in_n_d',{n:o.exp-S.day})}</div><div class="terms">${terms(o)}</div>${covList({covs:o.covs,start:S.day,base:{sub:S.links.filter(x=>x.sub).length}})}<div class="btns" style="margin-top:6px">${btn(tr('bank.take_the_money'),'takeLoan',{id:o.id},'pink')}${btn(tr('common.no_thanks'),'declineLoan',{id:o.id},'ghost sm')}</div></div></div>`;}
h+=`<h3 style="font-size:18px;margin-top:14px">${tr('common.your_loans')}</h3>`;
if(!S.loans.length)h+=`<p class="empty">${tr('bank.debt_free_your_accountant_is')}</p>`;
for(const l of S.loans){const B=BANKS[l.bank];const cost=repayCost(l,B);
h+=`<div class="loan"><span class="logo" style="--c:${B.col}">${initials(B)}</span><div class="grow"><div class="nm">${esc(B.name)} · ${fmt$(l.amount)}</div>
${B.equity?`<div class="meta">${tr('bank.taking_pct_of_your_revenue_every',{pct:pct(l.share)})}</div>`:`<div class="kv"><span>${tr('common.still_owed')}</span><b>${fmt$(l.bal)}</b></div><div class="bar me"><i style="width:${Math.min(100,(1-l.bal/l.amount)*100)}%"></i></div><div class="meta">${loanLine(l)}</div>`}
${covList(l)}${l.breach>=1?`<div class="why">${trn('bank.condition_broken_for_n_day',l.breach)} ${l.breach<10?tr('bank.penalty_in_n_days',{n:10-l.breach}):tr('bank.penalties_are_running')}</div>`:''}
<div class="btns" style="margin-top:6px">${btn(UI.confirm===l.id?tr('bank.really_pay_price',{price:fmt$(cost)}):B.equity?tr('bank.buy_them_out_price',{price:fmt$(cost)}):tr('bank.repay_early_price_incl_2_fee',{price:fmt$(cost)}),'repayLoan',{id:l.id},UI.confirm===l.id?'red sm':'sm',S.cash<cost)}</div></div></div>`;}
if(h!==UI._bh){UI._bh=h;$('bankCard').innerHTML=h;}
}

View file

@ -0,0 +1,9 @@
function renderHint(){
const hn=$('hint');if(!S||UI.hintOff||(S.tut!==undefined&&S.tut!==null)||(innerWidth<760&&(UI.sel||UI.leftOpen)&&!(UI.drag&&UI.drag.mode==='link'))){hn.hidden=true;return;}
let t='';
if(UI.drag&&UI.drag.mode==='link')t=UI.snap?tr('hint.release_to_plan_a_link'):tr('hint.drag_onto_another_city');
else if(!S.links.length&&S.done.tr)t=tr('hint.tip_drag_from_your_pink_router');
else if(!S.done.bb)t=tr('hint.tap_your_city_then_launch_broadband');
hn.textContent=t;hn.hidden=!t;
}