Merge #185: auto sale + auto repair automation (Logfro)

This commit is contained in:
Frederic Jung 2026-10-28 15:23:07 +01:00
commit 35fb35103f
No known key found for this signature in database
16 changed files with 443 additions and 7 deletions

View file

@ -24,6 +24,8 @@ All notable changes to this project are documented here. The project follows
- Attacks can now use Memcached amplification or an ACK flood. Flowspec catches the former; the latter need mitigation.
- Set the number of each optic model directly on land and subsea fiber links. Apply a whole change at once, with its total price shown before buying; removed optics return to the spares shelf.
- Order PNIs with one network or every network at all shared POPs from the NOC Traffic tab: choose a port size, review the total cost, and add missing connections or upgrade smaller ones in one go. Each network keeps its own smallest PNI size and delivery time.
- Toggle auto-accept in Deals to check ready sales every five real seconds, including their requirements and available service capacity, with a countdown beside eligible Accept buttons.
- Toggle auto-pay repairs in the NOC to pay for affordable rush repairs automatically while the game runs.
## [1.36.0] — 2026-10-28

View file

@ -14,6 +14,11 @@
"action_helpers.too_far_even_at_its_slowest":"Zu weit, selbst in der langsamsten Einstellung: Ein optischer Abschnitt ist hier {span} km lang, die Reichweite beträgt {max} km. Füge einen Regenerator-Standort hinzu (Line System).",
"action_helpers.unlocks_at_customer_level_n":"Wird ab Kundenlevel {n} freigeschaltet.",
"actions.your_router_can_t_take_a":"<b>Dein Router kann keinen {port}-Port aufnehmen.</b><br>Rüste ihn im Tab Infra auf.",
"automation.auto_accept_sales":"Deals automatisch annehmen: {state}",
"automation.auto_pay_repairs":"Reparaturen automatisch zahlen: {state}",
"automation.next_auto_check":"Zeit bis zur nächsten automatischen Prüfung der Anforderungen.",
"automation.repairs_when_affordable":"Zahlt während des Spiels automatisch Express-Reparaturen, wenn du sie dir leisten kannst.",
"automation.sales_every_five_seconds":"Alle 5 Sekunden während des Spiels: Nur Angebote, deren Anforderungen und Kapazität bereit sind, werden angenommen.",
"badges.a_petabit_a_second":"Ein Petabit pro Sekunde",
"badges.a_secret_badge":"Ein geheimes Abzeichen",
"badges.attend_a_conference":"Besuche eine Konferenz.",

View file

@ -12,6 +12,11 @@
"action_helpers.too_far_even_at_its_slowest":"Demasiado lejos incluso en su ajuste más lento: aquí un tramo óptico mide {span} km y el alcance es de {max} km. Añade un sitio regenerador (Sistema de línea).",
"action_helpers.unlocks_at_customer_level_n":"Se desbloquea en el nivel de cliente {n}.",
"actions.your_router_can_t_take_a":"<b>Tu router no admite un puerto de {port}.</b><br>Mejóralo en la pestaña Infra.",
"automation.auto_accept_sales":"Ventas automáticas: {state}",
"automation.auto_pay_repairs":"Reparaciones pagadas auto: {state}",
"automation.next_auto_check":"Tiempo hasta la próxima comprobación automática de requisitos.",
"automation.repairs_when_affordable":"Mientras juegas, paga automáticamente las reparaciones urgentes disponibles si hay fondos suficientes.",
"automation.sales_every_five_seconds":"Cada 5 segundos mientras juegas, acepta solo ofertas cuyos requisitos se cumplan y tengan capacidad de servicio disponible.",
"badges.a_petabit_a_second":"Un petabit por segundo",
"badges.a_secret_badge":"Una insignia secreta",
"badges.attend_a_conference":"Asiste a una conferencia.",

View file

@ -12,6 +12,11 @@
"action_helpers.too_far_even_at_its_slowest":"Trop loin, même au débit le plus lent : ici une portée optique fait {span} km et l’optique va jusqu’à {max} km. Ajoute un site de régénération (Système de ligne).",
"action_helpers.unlocks_at_customer_level_n":"Se débloque au niveau client {n}.",
"actions.your_router_can_t_take_a":"<b>Ton routeur ne supporte pas de port {port}.</b><br>Mets-le à niveau dans l’onglet Infra.",
"automation.auto_accept_sales":"Ventes automatiques : {state}",
"automation.auto_pay_repairs":"Réparations payées auto : {state}",
"automation.next_auto_check":"Temps avant la prochaine vérification automatique des conditions.",
"automation.repairs_when_affordable":"Pendant le jeu, paie automatiquement les réparations urgentes disponibles si les fonds suffisent.",
"automation.sales_every_five_seconds":"Toutes les 5 secondes pendant le jeu, accepte uniquement les offres dont les conditions sont remplies et la capacité de service disponible.",
"badges.a_petabit_a_second":"Un pétabit par seconde",
"badges.a_secret_badge":"Un badge secret",
"badges.attend_a_conference":"Participe à une conférence.",

View file

@ -12,6 +12,11 @@
"action_helpers.too_far_even_at_its_slowest":"Troppo lontano anche alla velocità più bassa: qui una tratta ottica è di {span} km e l’ottica arriva a {max} km. Aggiungi un sito di rigenerazione (Sistema di linea).",
"action_helpers.unlocks_at_customer_level_n":"Si sblocca al livello cliente {n}.",
"actions.your_router_can_t_take_a":"<b>Il tuo router non regge una porta {port}.</b><br>Aggiornalo nella scheda Infra.",
"automation.auto_accept_sales":"Vendite automatiche: {state}",
"automation.auto_pay_repairs":"Riparazioni a pagamento auto: {state}",
"automation.next_auto_check":"Tempo fino alla prossima verifica automatica dei requisiti.",
"automation.repairs_when_affordable":"Durante il gioco, paga automaticamente le riparazioni urgenti disponibili se hai abbastanza fondi.",
"automation.sales_every_five_seconds":"Ogni 5 secondi durante il gioco, accetta solo le offerte con requisiti soddisfatti e capacità di servizio disponibile.",
"badges.a_petabit_a_second":"Un petabit al secondo",
"badges.a_secret_badge":"Un badge segreto",
"badges.attend_a_conference":"Partecipa a una conferenza.",

View file

@ -12,6 +12,11 @@
"action_helpers.too_far_even_at_its_slowest":"Longe demais até na configuração mais lenta: um span óptico aqui tem {span} km e ela alcança {max} km. Adicione um site de regeneração (Line system).",
"action_helpers.unlocks_at_customer_level_n":"Desbloqueia no nível de cliente {n}.",
"actions.your_router_can_t_take_a":"<b>Seu router não aguenta uma porta {port}.</b><br>Faça upgrade na aba Infra.",
"automation.auto_accept_sales":"Vendas automáticas: {state}",
"automation.auto_pay_repairs":"Reparações pagas auto: {state}",
"automation.next_auto_check":"Tempo até à próxima verificação automática dos requisitos.",
"automation.repairs_when_affordable":"Durante o jogo, paga automaticamente as reparações urgentes disponíveis quando há fundos suficientes.",
"automation.sales_every_five_seconds":"A cada 5 segundos durante o jogo, aceita apenas ofertas com os requisitos cumpridos e capacidade de serviço disponível.",
"badges.a_petabit_a_second":"Um petabit por segundo",
"badges.a_secret_badge":"Um badge secreto",
"badges.attend_a_conference":"Participe de uma conferência.",

View file

@ -1,6 +1,6 @@
function newGame(name,home){
S={v:1,name,asn:200000+Math.floor(_rand()*15000),home,day:0,cash:START_CASH,
ltv:2,t1v:3,auV:1,seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{},pairMet:{},
ltv:2,t1v:3,auV:1,autoSales:false,autoRepair:false,seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{},pairMet:{},
done:{},inc:[],ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',capDeal:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,inbox:{items:[],down:{},tiny:{},rep:0,bot:false,log:[],seq:0},hw:{}};
}

View file

@ -0,0 +1,36 @@
/* Optional operators use the same sales and repair actions as the player. */
const AUTO_SALES_MS=5000;
function autoSalesSeconds(now=performance.now()){if(!S||!S.autoSales)return null;
const left=UI.autoGame===S&&autoActive()?AUTO_SALES_MS-(now-UI.autoSalesAt):AUTO_SALES_MS;
return Math.max(1,Math.min(AUTO_SALES_MS/1000,Math.ceil(left/1000)));}
function autoCountdownReady(o){if(!S||!S.autoSales||!o||!(o.exp>S.day)||!bCities(o).every(popUp)||!reqOk(o))return false;
const inc=S.inc.map(i=>i.id).join('|');let c=UI.autoReady;
// Share capacity trials between views and keep them until the next check, action or incident.
if(!c||c.s!==S||c.at!==UI.autoSalesAt||c.inc!==inc||c.event!==S.nextEvent)c=UI.autoReady={s:S,at:UI.autoSalesAt,inc,event:S.nextEvent,offers:new Map()};
if(!c.offers.has(o))c.offers.set(o,!!autoOffer(o));return c.offers.get(o);}
function autoAcceptLabel(o){return tr('common.accept')+(S.autoSales?` <small data-auto-sales="${esc(o.id)}" title="${esc(tr('automation.next_auto_check'))}">${autoCountdownReady(o)?`(${autoSalesSeconds()})`:''}</small>`:'');}
function renderAutoCountdown(now=performance.now()){const n=autoSalesSeconds(now);if(UI.autoCount===n&&UI.autoCountResult===R)return;UI.autoCount=n;UI.autoCountResult=R;
const offers=new Map((S?S.offers:[]).map(o=>[o.id,o]));
for(const el of document.querySelectorAll('[data-auto-sales]'))el.textContent=n!==null&&autoCountdownReady(offers.get(el.dataset.autoSales))?`(${n})`:'';}
function offerCustomer(o){return {id:o.id,city:o.city,city2:o.city2||null,reqs:o.reqs||[],latMax:o.latMax||null,route:BIZ_T[o.type].scenic?'scenic':BIZ_T[o.type].lat?'fast':'normal',name:o.name,type:o.type,bw:o.bw,rate:o.rate,mood:100,since:S.day,sites:o.sites||null,start:o.start,dur:o.dur,fee:o.fee,link:o.link,slots:o.slots||0,what:o.what,prov:o.prov,due:BIZ_T[o.type].cap?S.day+o.win:undefined};}
function autoOffer(o){if(!o||!own(BIZ_T,o.type)||!(o.exp>S.day)||!(o.bw>0)||o.rate<0||!bCities(o).length||!bCities(o).every(popUp)||!reqOk(o))return null;
const T=BIZ_T[o.type],b=offerCustomer(o);if(T.event&&(!(o.start>S.day)||!(o.dur>0)))return null;
if(o.type==='capfib'&&S.biz.some(x=>x.type==='capfib'&&capPend(x)&&!x.link&&((x.city===o.city&&x.city2===o.city2)||(x.city===o.city2&&x.city2===o.city))))return null;
if(T.fiber){const l=o.type==='capfib'?capFibLink(b):S.links.find(x=>x.id===o.link);if(!l)return null;b.link=l.id;
if(!fiberOk(b)||(o.type==='wwave'&&(!(o.slots>0)||freeCh(l)<o.slots))||(o.type==='dfpair'&&!pairFree(l))||
(o.type==='pairs'&&(!l.own||S.biz.some(x=>x.link===l.id&&['pairs','capfib','dfpair'].includes(x.type)))))return null;}
const state=S,result=R,hot=UI.hotMap,future=S.biz.some(x=>BIZ_T[x.type].event&&x.start>S.day);
// Trial the added demand before signing; failed trials leave the live game untouched.
try{S={...S,biz:S.biz};
// shortcut: future events reserve capacity together; use per-date trials if separate bookings must share capacity.
if(future){S.biz=S.biz.map(x=>BIZ_T[x.type].event&&x.start>S.day?{...x,start:S.day}:x);compute();}
const healthy=S.biz.filter(x=>!bizWhy(x).length);if(T.event)b.start=S.day;if(T.cap)b.live=true;S.biz=S.biz.concat(b);compute();
return !bizWhy(b).length&&healthy.every(x=>!bizWhy(x).length)?b:null;
}finally{S=state;R=result;UI.hotMap=hot;b.start=o.start;if(T.cap)delete b.live;}}
function autoActive(){return !!(S&&UI.started&&!S.lost&&UI.speed&&$('modal').hidden&&document.visibilityState==='visible');}
function automationTick(now){if(UI.autoGame!==S){UI.autoGame=S;UI.autoSalesAt=now;}
if(!autoActive()){UI.autoSalesAt=now;return;}
if(S.autoRepair&&S.inc.length){purgeInc();for(const i of S.inc.slice()){if(!autoActive())break;
if(i.type!=='ddos'&&i.until>S.day&&i.cost>0&&i.cost<=S.cash&&!(i.slow&&i.rushed))ACT.fixInc({id:i.id});}}
if(!S.autoSales||!autoActive()){UI.autoSalesAt=now;return;}if(now-UI.autoSalesAt<AUTO_SALES_MS)return;
UI.autoSalesAt=now;for(const o of S.offers.slice()){if(!autoActive())break;ACT.accept({id:o.id,auto:true});}}

View file

@ -9,6 +9,7 @@ function sanitize(s){
['pops','ixp','rs','peers','myIx','done','ev','stats','ixn','ixPref','ixSite','confReg','ach','pairMet'].forEach(obj);
s.v=1;s.name=String(s.name==null?'Packet Pals':s.name).slice(0,24);s.day=int(s.day,0,1e7,0);s.cash=num(s.cash,0);s.asn=int(s.asn,1,4294967294,200000);
s.priceMul=num(s.priceMul,1);s.nextFail=num(s.nextFail,s.day+45);s.nextEvent=num(s.nextEvent,s.day+40);s.lvl=int(s.lvl,1,LEVELS.length,1);s.neg=int(s.neg,0,1e7,0);s.loanStrikes=int(s.loanStrikes,0,1e3,0);
s.autoSales=s.autoSales===true;s.autoRepair=s.autoRepair===true;
for(const k of Object.keys(s.stats)){const v=s.stats[k];if(k==='by'||k==='f'){if(!v||typeof v!=='object')s.stats[k]={};else for(const j of Object.keys(v))v[j]=num(v[j],0);}else if(typeof v!=='boolean')s.stats[k]=num(v,0);}
for(const k of ['survived','incidents','peak'])s.stats[k]=num(s.stats[k],0);
for(const c of Object.keys(s.pops)){const p=s.pops[c];if(!isCity(c)||!p||typeof p!=='object'){delete s.pops[c];continue;}p.routers=int(p.routers,1,RMAX,1);if(p.rupDay!==undefined)p.rupDay=num(p.rupDay,-1);if(p.rgen!==undefined)p.rgen=int(p.rgen,0,RG.length-1,0);p.down=num(p.down,0);if(p.bb&&typeof p.bb==='object')p.bb.d=num(p.bb.d,0);else p.bb=null;}

View file

@ -4,7 +4,8 @@ Object.assign(ACT,{
const T=BIZ_T[t],nm=()=>{const list=T.names.filter(n=>!S.usedNames.includes(n)),n=list.length?pick(list):pick(T.names);useName(n);return n;};
// A capacity broker finds a buyer at once and keeps 10% of the monthly price.
const o=fiberOffer(t,l,nm,0.9);o.broker=true;S.offers.push(o);toast(tr('customers.listed_with_a_capacity_broker_name',{name:esc(o.name),what:esc(o.what)}),'good');sfx('click');after();},
accept:({id})=>{const o=S.offers.find(x=>x.id===id);if(!o)return;if(!bHas(o)){toast(tr('customers.you_need_a_pop_in_every'),'bad');return;}
autoToggle:({k})=>{if(k!=='autoSales'&&k!=='autoRepair')return;S[k]=!S[k];if(k==='autoSales'){UI.autoGame=S;UI.autoSalesAt=performance.now();}sfx('click');after();},
accept:({id,auto=false})=>{const o=S.offers.find(x=>x.id===id);if(!o)return;const customer=auto?(S.autoSales&&autoOffer(o)):offerCustomer(o);if(!customer)return;if(!bHas(o)){toast(tr('customers.you_need_a_pop_in_every'),'bad');return;}
if(o.type==='wwave'){const l=S.links.find(x=>x.id===o.link);if(!l||chMax(l)-(l.ch||[]).length-soldSlots(l)<o.slots){toast(tr('customers.not_enough_free_channels_on_that'),'bad');return;}}
if(BIZ_T[o.type].event&&S.day>=o.start){toast(tr('customers.too_late_the_event_has_already'),'bad');return;}
// A carrier renting more alien waves on a fiber it already rents grows its contract, like a real order for extra waves,
@ -12,7 +13,7 @@ Object.assign(ACT,{
const more=o.type==='wwave'&&S.biz.find(b=>b.type==='wwave'&&b.link===o.link&&b.name===o.name);
if(more){const l=S.links.find(x=>x.id===o.link);S.offers=S.offers.filter(x=>x!==o);more.slots=(more.slots||0)+(o.slots||0);more.rate+=o.rate;if(l)more.what=wwWhat(l,more.slots);
floater(CITY[o.city].x,CITY[o.city].y-30,tr('common.signed'),'#16A866');sfx('coin');after();return;}
S.offers=S.offers.filter(x=>x!==o);S.biz.push({id:o.id,city:o.city,city2:o.city2||null,reqs:o.reqs||[],latMax:o.latMax||null,route:BIZ_T[o.type].scenic?'scenic':BIZ_T[o.type].lat?'fast':'normal',name:o.name,type:o.type,bw:o.bw,rate:o.rate,mood:100,since:S.day,sites:o.sites||null,start:o.start,dur:o.dur,fee:o.fee,link:o.link,slots:o.slots||0,what:o.what,prov:o.prov,due:BIZ_T[o.type].cap?S.day+o.win:undefined});
S.offers=S.offers.filter(x=>x!==o);S.biz.push(customer);
floater(CITY[o.city].x,CITY[o.city].y-30,tr('common.signed'),'#16A866');sfx('coin');after();},
decline:({id})=>{S.offers=S.offers.filter(x=>x.id!==id);after();},
dropBiz:({id})=>{const b0=S.biz.find(x=>x.id===id);if(!b0)return;if(BIZ_T[b0.type].event&&S.day>=b0.start){toast(tr('customers.the_event_is_already_running_the'),'bad');sfx('err');return;}if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.biz=S.biz.filter(b=>b.id!==id);UI.confirm=null;after();},

View file

@ -22,7 +22,7 @@ function chWhy(l,o){const O=OPT[o];if(O.lvl>lvl())return tr('action_helpers.unlo
if((l.ch||[]).length+soldSlots(l)>=chMax(l))return soldSlots(l)?tr('action_helpers.sys_is_full_max_channels_sold',{sys:DF_SYS[l.sys].n,max:chMax(l),sold:soldSlots(l)}):tr('action_helpers.sys_is_full_max_channels',{sys:DF_SYS[l.sys].n,max:chMax(l)});
for(const c of [l.a,l.b]){const p=S.pops[c];if(p&&RG[p.rgen||0].cls<O.rg)return tr('action_helpers.needs_routers_with_pn_ports_or',{pn:RG[mainRG(O.rg)].pn,city:CITY[c].name});}return '';}
function bbCost(c){return 15000+CITY[c].P*20;}
function after(){if(S)purgeInc();compute();checkGoals();renderAll();if(S&&!$('dash').hidden)renderDash();save();}
function after(){UI.autoReady=null;if(S)purgeInc();compute();checkGoals();renderAll();if(S&&!$('dash').hidden)renderDash();save();}
const isTablet=()=>innerWidth>760&&innerWidth<=1200;
function selectLink(id){UI.sel={type:'link',id};UI.confirm=null;if(isTablet()||isPhone())UI.leftOpen=false;$('panel').classList.remove('full');renderPanel();renderLeft();}
function selectCity(c){UI.sel={type:'city',id:c};UI.confirm=null;if(isTablet()||isPhone())UI.leftOpen=false;const P=$('panel');if(P)P.classList.remove('full');if(!S.pops[c])UI.tab='cust';renderPanel();}

View file

@ -37,16 +37,18 @@ function renderLeft(){checkLayer();
h+=GOALS.map(g=>{const d=S.done[g.id]!==undefined,c=g===cur;return `<div class="goal ${d?'done':''} ${c?'cur':''}"><div class="ck">${d?'✓':''}</div><div><div class="gt">${esc(g.t)}</div>${c||!d?`<div class="gd">${esc(g.d)}</div>`:''}${!d&&g.r?`<div class="gr">${tr('hud_and_panels.reward_cash',{cash:fmt$(g.r)})}</div>`:''}</div></div>`;}).join('');
h+=badgeGrid();
}else if(UI.left==='deals'){
h+=`<div class="btns"><button class="b sm ${S.autoSales?'green':'ghost'}" data-act="autoToggle" data-args='{"k":"autoSales"}' aria-pressed="${S.autoSales}">${tr('automation.auto_accept_sales',{state:S.autoSales?tr('common.on'):tr('common.off')})}</button></div><p class="meta">${tr('automation.sales_every_five_seconds')}</p>`;
{const st=custStats();if(st.n)h+=`<div class="row" style="margin-bottom:8px"><div class="grow"><div class="nm">${tr('common.your_customers')} <span class="meta">${st.n} · ${tr('hud_and_panels.happiness_p',{p:Math.round(st.avg)})}</span></div><div class="bar ${moodCls(st.avg)}"><i style="width:${st.avg}%"></i></div>${st.unhappy?`<div class="why">${trn('hud_and_panels.n_unhappy_customer_price_mo_at',st.unhappy,{price:fmt$(st.risk)})}</div>`:''}</div>${btn(st.unhappy?tr('common.see_who'):tr('common.all_customers'),'custOpen',{sad:st.unhappy?1:0},st.unhappy?'pink sm':'ghost sm')}</div>`;}
h+=confSection();
{const lv=S.lvl||1,nx=LEVELS[lv];h+=`<div class="inc" style="background:#FFF6CF"><div class="nm">${tr('hud_and_panels.customer_level_lv_name',{lv,name:LEVELS[lv-1].n})}</div><div class="meta">${nx?tr('hud_and_panels.next_req_unlocks_what',{req:nx.req,what:lc1(nx.unlock)}):tr('common.every_customer_type_is_unlocked_go')}</div></div>`;}
if(!S.offers.length)h+=`<p class="empty">${tr('hud_and_panels.no_open_offers_right_now_businesses')}</p>`;
for(const o of S.offers.slice().sort((a,b)=>a.exp-b.exp)){const has=bHas(o);
h+=`<div class="row"><div class="grow"><div class="nm">${esc(o.name)}</div><div class="meta">${esc(BIZ_T[o.type].l)} · ${CITY[o.city].name}${o.city2?' ⇄ '+CITY[o.city2].name:''} · <b>${bTerms(o)}</b> · ${tr('ui.n_d_left',{n:o.exp-S.day})}${(o.reqs||[]).length?` · ${trn('hud_and_panels.n_special_requirement',o.reqs.length)}`:''}</div>${bRisk(o)}${reqList(o)}
<div class="btns">${has?btn(tr('common.accept'),'accept',{id:o.id},'green sm'):btn(tr('common.go_there'),'focusCity',{city:bCities(o).find(c=>!S.pops[c])},'ghost sm')}${btn(tr('common.decline'),'decline',{id:o.id},'ghost sm')}</div>${has?'':`<div class="why">${tr('hud_and_panels.needs_a_pop_in_cities',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}</div>`}</div></div>`;}
<div class="btns">${has?btn(autoAcceptLabel(o),'accept',{id:o.id},'green sm'):btn(tr('common.go_there'),'focusCity',{city:bCities(o).find(c=>!S.pops[c])},'ghost sm')}${btn(tr('common.decline'),'decline',{id:o.id},'ghost sm')}</div>${has?'':`<div class="why">${tr('hud_and_panels.needs_a_pop_in_cities',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}</div>`}</div></div>`;}
}else if(UI.left==='noc'){
h+=`<div class="btns" style="margin-bottom:8px">${btn(tr('hud_and_panels.open_noc_dashboard'),'dash',{},'pink')}${btn(tr('common.connections'),'connOpen',{},'')}${btn(tr('common.traceroute'),'trace',{},'')}</div>`;
h+=`<p class="lead">${tr('hud_and_panels.your_network_operations_center_every')}</p>`;
h+=`<div class="btns"><button class="b sm ${S.autoRepair?'green':'ghost'}" data-act="autoToggle" data-args='{"k":"autoRepair"}' aria-pressed="${S.autoRepair}">${tr('automation.auto_pay_repairs',{state:S.autoRepair?tr('common.on'):tr('common.off')})}</button></div><p class="meta">${tr('automation.repairs_when_affordable')}</p>`;
// Incidents come first, the ones you can fix with one click at the top (#63): no scrolling past hot ports to replace an optic.
for(const i of S.inc.filter(i=>i.type!=='ddos').sort((a,b)=>(b.cost?1:0)-(a.cost?1:0)||(b.impact||0)-(a.impact||0))){h+=`<div class="inc"><div class="nm">${incTitle(i.type)}</div><div class="meta">${esc(i.msg)}</div><div class="meta">${trn('hud_and_panels.auto_fix_in_n_day',i.until-S.day)}${i.impact?` · ${tr('hud_and_panels.g_lost',{g:fmtG(i.impact)})}`:''}</div>${i.cost?`<div class="btns">${btn(`${esc(i.fix||tr('common.rush_repair'))} ${fmt$(i.cost)}`,'fixInc',{id:i.id},'red sm',S.cash<i.cost)}</div>`:''}</div>`;}
h+=logSection();UI.logSeen=Date.now();

View file

@ -104,7 +104,7 @@ function dfPanel(l){
if(!bld){const sold=S.biz.filter(b=>b.link===l.id&&(b.type==='wwave'||b.type==='dfpair'||b.type==='pairs')),off=S.offers.find(o=>o.link===l.id),fc=freeCh(l);
h+=`<section><h3>${tr('link_panels.selling_spare_capacity')}</h3><p class="lead">${tr('link_panels.other_carriers_rent_what_you_do')}</p>
<div class="kv"><span>${tr('common.free_channels')}</span><b>${fc} / ${chMax(l)}</b></div>${sold.map(b=>`<div class="row"><div class="grow"><div class="nm">${esc(b.name)}</div><div class="meta">${esc(b.what||BIZ_T[b.type].l)} · ${tr('common.price_mo',{price:fmt$(b.rate)})}</div></div></div>`).join('')}
${off?`<div class="row"><div class="grow"><div class="nm">${esc(off.name)}</div><div class="meta">${esc(off.what)} · ${tr('common.price_mo',{price:fmt$(off.rate)})} · ${tr('ui.n_d_left',{n:off.exp-S.day})}${off.broker?' · '+tr('link_panels.via_a_capacity_broker'):''}</div></div>${btn(tr('common.accept'),'accept',{id:off.id},'pink sm')}</div>`:fc>=1||pairFree(l)?`<div class="btns">${btn(tr('link_panels.list_it_with_a_capacity_broker'),'advertise',{id:l.id},'sm')}</div>`:`<p class="note">${tr('link_panels.nothing_spare_to_sell_on_this')}</p>`}</section>`;}
${off?`<div class="row"><div class="grow"><div class="nm">${esc(off.name)}</div><div class="meta">${esc(off.what)} · ${tr('common.price_mo',{price:fmt$(off.rate)})} · ${tr('ui.n_d_left',{n:off.exp-S.day})}${off.broker?' · '+tr('link_panels.via_a_capacity_broker'):''}</div></div>${btn(autoAcceptLabel(off),'accept',{id:off.id},'pink sm')}</div>`:fc>=1||pairFree(l)?`<div class="btns">${btn(tr('link_panels.list_it_with_a_capacity_broker'),'advertise',{id:l.id},'sm')}</div>`:`<p class="note">${tr('link_panels.nothing_spare_to_sell_on_this')}</p>`}</section>`;}
h+=`<section><h3>${tr('common.optics')}</h3><p class="lead">${tr('link_panels.each_channel_is_a_pair_of')}</p>`;
if(l.own&&l.sub)h+=subUpgradePanel(l);
for(const k of Object.keys(OPT)){const O=OPT[k],n=(l.ch||[]).filter(x=>x===k).length,why=chWhy(l,k);
@ -121,7 +121,7 @@ function dfPanel(l){
}
function offersHere(c){
const os=S.offers.filter(o=>bCities(o).includes(c));if(!os.length)return '';
return `<section><h3>${tr('common.offers_here')}</h3>${os.map(o=>`<div class="row"><div class="grow"><div class="nm">${esc(o.name)}</div><div class="meta">${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}</div>${R.reach<0.99&&!BIZ_T[o.type].l2?`<div class="why">${tr('link_panels.they_need_the_full_internet_your',{pct:pct(R.reach)})}</div>`:''}${o.type==='scrub'&&!hasScrub()?`<div class="why">${tr('link_panels.needs_your_own_scrubbing_center')}</div>`:''}${bRisk(o)}${reqList(o)}${bHas(o)?'':`<div class="why">${tr('link_panels.needs_a_pop_in_cities_too',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}</div>`}</div>${bHas(o)?btn(tr('common.accept'),'accept',{id:o.id},'green sm'):''}${btn(tr('common.no'),'decline',{id:o.id},'ghost sm')}</div>`).join('')}</section>`;
return `<section><h3>${tr('common.offers_here')}</h3>${os.map(o=>`<div class="row"><div class="grow"><div class="nm">${esc(o.name)}</div><div class="meta">${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}</div>${R.reach<0.99&&!BIZ_T[o.type].l2?`<div class="why">${tr('link_panels.they_need_the_full_internet_your',{pct:pct(R.reach)})}</div>`:''}${o.type==='scrub'&&!hasScrub()?`<div class="why">${tr('link_panels.needs_your_own_scrubbing_center')}</div>`:''}${bRisk(o)}${reqList(o)}${bHas(o)?'':`<div class="why">${tr('link_panels.needs_a_pop_in_cities_too',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}</div>`}</div>${bHas(o)?btn(autoAcceptLabel(o),'accept',{id:o.id},'green sm'):''}${btn(tr('common.no'),'decline',{id:o.id},'ghost sm')}</div>`).join('')}</section>`;
}
function linkPanel(id){
const l=S.links.find(x=>x.id===id);if(!l){UI.sel=null;return '';}

View file

@ -10,6 +10,7 @@ function frame(now){
if(UI.panelsDue){UI.panelsDue=false;if(!pressing){renderPanel();renderLeft();if(!$('dash').hidden)renderDash();renderBank();}renderHint();}
if(S&&!S.lost&&$('modal').hidden&&UI.speed){acc+=dt*UI.speed;let n=0;while(acc>=DAY_MS&&n<4&&UI.speed){acc-=DAY_MS;try{dayTick();}catch(e){tickErr(e);}n++;}
if(n){UI.ticking=true;renderHUD();UI.ticking=false;UI.panelsDue=true;}}
try{automationTick(now);renderAutoCountdown();}catch(e){tickErr(e);}
if(UI.speed&&!(S&&S.lost))animT+=dt; /* paused = frozen dots, waves and clouds */
const t=animOn()?animT:0;
if(!(UI.mapHid=mapHidden())&&!mapStill(t,now)){try{draw(t);}catch(e){tickErr(e);}UI.drawnAt=now;}

View file

@ -13,6 +13,11 @@
"action_helpers.too_far_even_at_its_slowest":"Too far even at its slowest setting: an optical span here is {span} km and it reaches {max} km. Add a regen site (Line system).",
"action_helpers.unlocks_at_customer_level_n":"Unlocks at customer level {n}.",
"actions.your_router_can_t_take_a":"<b>Your router can't take a {port} port.</b><br>Upgrade it in the Infra tab.",
"automation.auto_accept_sales":"Auto-accept sales: {state}",
"automation.auto_pay_repairs":"Auto-pay repairs: {state}",
"automation.next_auto_check":"Time until the next automatic requirements check.",
"automation.repairs_when_affordable":"While playing, automatically pay for available rush repairs when you can afford them.",
"automation.sales_every_five_seconds":"Every 5 seconds while playing, accept only offers whose requirements and service capacity are ready.",
"badges.a_petabit_a_second":"A Petabit a Second",
"badges.a_secret_badge":"A secret badge",
"badges.attend_a_conference":"Attend a conference.",

363
tests/automation.test.js Normal file
View file

@ -0,0 +1,363 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
function setup(ev) {
ev("ACT.start({});S.cash=1e8;S.offers=[];S.biz=[];S.nextFail=S.nextEvent=1e6;for(const g of GOALS)S.done[g.id]=0;S.pops.fra.rgen=3;ACT.buyTransit({city:'fra',net:'lvl',tier:1});compute()");
}
function offer(ev, id, extra = {}) {
ev(`S.offers.push(${JSON.stringify({ id, city: 'fra', name: id, type: 'dia', bw: 1, rate: 600, reqs: [], exp: 30, ...extra })})`);
}
test('auto-accept waits five real seconds at every game speed and the toggle stops it', () => {
for (const speed of [0.5, 1, 2, 4, 8]) {
const { ev, dom, errors } = load();
setup(ev);
offer(ev, 'first');
ev("ACT.autoToggle({k:'autoSales'});UI.autoSalesAt=1000");
const start = ev('UI.autoSalesAt');
ev(`UI.speed=${speed};automationTick(${start + 4999})`);
assert.equal(ev('S.biz.length'), 0, speed);
ev(`automationTick(${start + 5000})`);
assert.equal(ev('S.biz[0].id'), 'first', speed);
offer(ev, 'second');
ev(`automationTick(${start + 9999})`);
assert.equal(ev('S.biz.length'), 1, speed);
ev(`automationTick(${start + 10000})`);
assert.equal(ev('S.biz.length'), 2, speed);
ev("ACT.autoToggle({k:'autoSales'})");
offer(ev, 'off');
ev(`automationTick(${start + 20000});ACT.accept({id:'off',auto:true})`);
assert.equal(ev('S.biz.length'), 2, speed);
assert.equal(ev('S.offers[0].id'), 'off', speed);
assert.deepEqual(errors, []);
dom.window.close();
}
});
test('Accept buttons share a real-time countdown in Deals, city offers and fiber broker offers', () => {
const { ev, dom, errors } = load();
setup(ev);
offer(ev, 'ready');
offer(ev, 'waiting', { reqs: ['gen'] });
ev("window.testNow=1000;performance.now=()=>testNow;ACT.leftTab({t:'deals'});UI.sel={type:'city',id:'fra'};UI.tab='cust';UI.leftOpen=true;renderAll()");
assert.equal(dom.window.document.querySelectorAll('[data-auto-sales]').length, 0);
ev("ACT.autoToggle({k:'autoSales'});renderAutoCountdown()");
const counts = () => [...dom.window.document.querySelectorAll('[data-auto-sales]')];
const readyCounts = () => counts().filter(el => el.dataset.autoSales === 'ready');
assert.ok(readyCounts().length >= 2, 'Deals and the city panel both show it');
assert.ok(readyCounts().every(el => el.textContent === '(5)'));
assert.ok(counts().filter(el => el.dataset.autoSales === 'waiting').every(el => el.textContent === ''), 'unmet requirements have no countdown');
ev('testNow=2001;renderAutoCountdown()');
assert.ok(readyCounts().every(el => el.textContent === '(4)'));
ev('testNow=3000;UI.speed=8;renderAutoCountdown()');
assert.ok(readyCounts().every(el => el.textContent === '(3)'));
ev('UI.speed=0.5;renderAll();renderAutoCountdown()');
assert.ok(readyCounts().every(el => el.textContent === '(3)'), 'game speed and re-rendering leave the real-time clock alone');
assert.match(dom.window.document.querySelector('#leftBody [data-act="accept"]').textContent, /Accept \(3\)/);
ev("ACT.buildPop({city:'ams'});S.links.push({id:'fiber',a:'fra',b:'ams',kind:'df',sys:'lite',ch:[],own:true,km:450,ready:0,cut:0,mo:1})");
offer(ev, 'broker', { type: 'wwave', city2: 'ams', link: 'fiber', slots: 1, what: 'One wave' });
ev("compute();UI.sel={type:'link',id:'fiber'};renderPanel()");
const broker = dom.window.document.querySelector('#panelBody [data-act="accept"] [data-auto-sales]');
assert.ok(broker);
assert.equal(broker.textContent, '(3)');
ev('testNow=6000;automationTick(testNow);renderAutoCountdown()');
assert.equal(ev("S.biz.some(b=>b.id==='ready')"), true);
assert.equal(ev("S.offers.some(o=>o.id==='waiting')"), true, 'the countdown does not bypass requirements');
offer(ev, 'next-ready');
ev('renderAll();renderAutoCountdown()');
assert.ok(counts().filter(el => el.dataset.autoSales === 'next-ready').every(el => el.textContent === '(5)'), 'the next check starts a fresh countdown');
ev("ACT.autoToggle({k:'autoSales'});renderAutoCountdown()");
assert.equal(counts().length, 0);
assert.deepEqual(errors, []);
dom.window.close();
});
test('only ready offers get a countdown, including after requirements or capacity change', () => {
const { ev, dom, errors } = load();
setup(ev);
offer(ev, 'ready');
offer(ev, 'needs-generator', { reqs: ['gen'] });
offer(ev, 'too-big', { bw: 1000 });
offer(ev, 'expired', { exp: 0 });
ev("window.testNow=1000;performance.now=()=>testNow;ACT.leftTab({t:'deals'});ACT.autoToggle({k:'autoSales'});renderAutoCountdown()");
const count = id => dom.window.document.querySelector(`#leftBody [data-auto-sales="${id}"]`).textContent;
assert.equal(count('ready'), '(5)');
assert.equal(count('needs-generator'), '');
assert.equal(count('too-big'), '');
assert.equal(count('expired'), '');
ev('S.pops.fra.gen=true;after()');
assert.equal(count('needs-generator'), '(5)', 'becoming eligible shows the timer');
ev('S.pops.fra.gen=false;compute();renderAutoCountdown()');
assert.equal(count('needs-generator'), '', 'a requirement becoming false hides it immediately');
ev("S.offers.find(o=>o.id==='too-big').bw=2;after()");
assert.equal(count('too-big'), '(5)', 'actions invalidate the capacity preview');
ev('testNow=6000;automationTick(testNow);renderAutoCountdown()');
assert.equal(ev("S.offers.some(o=>o.id==='needs-generator')"), true, 'acceptance checks requirements again');
assert.deepEqual(errors, []);
dom.window.close();
});
test('readiness trials are shared between views and are not repeated for every redraw', () => {
const { ev, dom, errors } = load();
setup(ev);
offer(ev, 'ready');
ev("window.testNow=1000;performance.now=()=>testNow;ACT.leftTab({t:'deals'});UI.sel={type:'city',id:'fra'};UI.tab='cust';window.originalAutoOffer=autoOffer;window.trials=0;window.autoOffer=o=>{trials++;return originalAutoOffer(o)};ACT.autoToggle({k:'autoSales'})");
assert.equal(ev('trials'), 1);
ev('renderAll();compute();renderAll();renderAutoCountdown()');
assert.equal(ev('trials'), 1, 'ordinary routing refreshes reuse the preview');
ev('after()');
assert.equal(ev('trials'), 2, 'a real action refreshes readiness');
ev('window.autoOffer=originalAutoOffer');
assert.deepEqual(errors, []);
dom.window.close();
});
test('auto-accept leaves unready and expired offers alone without failure notifications', () => {
const { ev, dom, errors } = load();
setup(ev);
offer(ev, 'generator', { reqs: ['gen'] });
offer(ev, 'missing-pop', { city: 'ams' });
offer(ev, 'scrub', { type: 'scrub' });
offer(ev, 'expired', { exp: 0 });
offer(ev, 'ipv6', { reqs: ['ipv6'] });
const log = ev('S.log.length');
ev('S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)');
assert.equal(ev('S.biz.length'), 0);
assert.equal(ev('S.offers.length'), 5);
assert.equal(ev('S.log.length'), log, 'no repeated failed manual-action toasts');
ev('S.pops.fra.gen=true;compute();automationTick(10000)');
assert.equal(ev('S.biz.length'), 1);
assert.equal(ev('S.biz[0].id'), 'generator');
// Manual acceptance keeps its existing sign-now, provision-later behavior.
ev("ACT.accept({id:'scrub'})");
assert.equal(ev("S.biz.some(b=>b.id==='scrub')"), true);
assert.deepEqual(errors, []);
dom.window.close();
});
test('the trial includes new bandwidth and later offers cannot overbook earlier accepted sales', () => {
const { ev, dom, errors } = load();
setup(ev);
offer(ev, 'one', { bw: 60 });
offer(ev, 'two', { bw: 60 });
const state = ev('JSON.stringify(S)');
ev('window.beforeState=S;window.beforeResult=R;window.beforeHot=UI.hotMap');
assert.equal(ev('!!autoOffer(S.offers[0])'), true);
assert.equal(ev('JSON.stringify(S)'), state);
assert.equal(ev('S===beforeState&&R===beforeResult&&UI.hotMap===beforeHot'), true);
ev('S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)');
assert.equal(ev('S.biz.length'), 1);
assert.equal(ev('S.offers[0].id'), 'two');
assert.ok(ev('bizSf(S.biz[0])') >= 0.95);
assert.deepEqual(errors, []);
dom.window.close();
});
test('auto-accept checks actual circuits, latency and NNI capacity', () => {
const { ev, dom, errors } = load();
setup(ev);
ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;compute()");
offer(ev, 'circuit', { type: 'hft', city2: 'ams', bw: 10, latMax: 50, reqs: ['lat'] });
assert.equal(ev('!!autoOffer(S.offers[0])'), false, 'POPs alone are not a circuit');
ev("S.links.push({id:'path',a:'fra',b:'ams',kind:'wave',tier:1,km:450,sub:false,cut:0,mo:1});compute()");
assert.equal(ev('!!autoOffer(S.offers[0])'), true);
ev('S.offers[0].latMax=0.1');
assert.equal(ev('!!autoOffer(S.offers[0])'), false, 'latency budget must pass');
ev("S.offers=[];window.fabric=FABS.find(f=>f.cities.includes('fra')).id;ACT.buyNni({city:'fra',prov:fabric,tier:0})");
const prov = ev('fabric');
const bandwidth = ev('NNI[0].g * 0.75');
offer(ev, 'fabric-one', { type: 'fabip', prov, bw: bandwidth, reqs: ['nni'] });
offer(ev, 'fabric-two', { type: 'fabip', prov, bw: bandwidth, reqs: ['nni'] });
// Transit has enough headroom, so the second rejection is the shared NNI port.
ev("S.transit[0].tier=4;compute();S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)");
assert.equal(ev('S.biz.length'), 1);
assert.equal(ev('S.offers[0].id'), 'fabric-two');
assert.ok(ev("nniUsed('fra',fabric)<=NNI[0].g"));
assert.deepEqual(errors, []);
dom.window.close();
});
test('new circuits do not take service away from healthy signed customers', () => {
const { ev, dom, errors } = load();
setup(ev);
ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;S.links.push({id:'path',a:'fra',b:'ams',kind:'wave',tier:1,km:450,sub:false,cut:0,mo:1});S.transit[0].city='ams';compute()");
offer(ev, 'existing', { bw: 80 });
ev("ACT.accept({id:'existing'})");
offer(ev, 'new-circuit', { type: 'l2vpn', city2: 'ams', bw: 50 });
assert.equal(ev('bizWhy(S.biz[0]).length'), 0);
assert.equal(ev('!!autoOffer(S.offers[0])'), false);
assert.ok(ev('bizSf(S.biz[0])') >= 0.95, 'failed preview leaves the old routing result intact');
assert.deepEqual(errors, []);
dom.window.close();
});
test('fiber sales check live equipment and free spectrum, and repeated carrier orders still merge', () => {
const { ev, dom, errors } = load();
setup(ev);
ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;S.links=[{id:'fiber',a:'fra',b:'ams',kind:'df',own:true,sys:'lite',ch:Array(14).fill('zr4'),km:450,sub:false,ready:0,cut:0,mo:1}];S.biz=[{id:'old',name:'Same Carrier',type:'wwave',city:'fra',city2:'ams',link:'fiber',bw:1,rate:1000,slots:1,reqs:[],mood:100,since:0}];compute()");
offer(ev, 'full', { type: 'wwave', city2: 'ams', link: 'fiber', slots: 2 });
assert.equal(ev('!!autoOffer(S.offers[0])'), false);
ev("S.offers[0].slots=1;S.offers[0].name='Same Carrier';S.links[0].eqDown=10;compute()");
assert.equal(ev('!!autoOffer(S.offers[0])'), false, 'a broken amplifier prevents a wave sale');
ev('S.links[0].eqDown=0;compute();S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)');
assert.equal(ev('S.biz.length'), 1);
assert.equal(ev('S.biz[0].slots'), 2);
assert.equal(ev('S.biz[0].rate'), 1600);
assert.equal(ev('freeCh(S.links[0])'), 0);
assert.deepEqual(errors, []);
dom.window.close();
});
test('capacity pair sales need completed infrastructure and reserve it for the accepted contract', () => {
const { ev, dom, errors } = load();
setup(ev);
offer(ev, 'pairs', { type: 'capfib', city2: 'ams', slots: 2, win: 90 });
assert.equal(ev('!!autoOffer(S.offers[0])'), false);
ev("ACT.buildPop({city:'ams'});S.links=[{id:'own',a:'fra',b:'ams',kind:'df',own:true,sys:'roadm',ch:[],km:450,sub:false,ready:0,cut:0,mo:1}];compute()");
assert.equal(ev('!!autoOffer(S.offers[0])'), true);
ev('S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)');
assert.equal(ev('S.biz[0].link'), 'own');
assert.equal(ev('capPend(S.biz[0])'), true, 'normal delivery handover still happens on a game day');
offer(ev, 'second-pairs', { type: 'capfib', city2: 'ams', slots: 2, win: 90 });
assert.equal(ev('!!autoOffer(S.offers[0])'), false, 'the same trench cannot be promised twice');
assert.deepEqual(errors, []);
dom.window.close();
});
test('future event demand is tested before signing, with booked events reserving headroom', () => {
const { ev, dom, errors } = load();
setup(ev);
offer(ev, 'event', { type: 'event', bw: 80, rate: 0, start: 10, dur: 3, fee: 5000, exp: 9 });
assert.equal(ev('!!autoOffer(S.offers[0])'), true);
ev('S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)');
assert.equal(ev('S.biz[0].start'), 10, 'the trial does not move the actual event date');
assert.equal(ev('R.cityDem.fra'), 0);
offer(ev, 'too-large', { bw: 30 });
assert.equal(ev('!!autoOffer(S.offers[0])'), false);
ev('S.offers[0].bw=10');
assert.equal(ev('!!autoOffer(S.offers[0])'), true);
assert.equal(ev('S.biz[0].start'), 10);
assert.equal(ev('R.cityDem.fra'), 0);
assert.deepEqual(errors, []);
dom.window.close();
});
test('failed capacity trials restore game, routing and map state even when compute throws', () => {
const { ev, dom, errors } = load();
setup(ev);
offer(ev, 'ready');
ev("window.beforeState=S;window.beforeResult=R;window.beforeHot=UI.hotMap;window.originalCompute=compute;window.compute=()=>{throw new Error('trial failed')}");
assert.throws(() => ev('autoOffer(S.offers[0])'), /trial failed/);
assert.equal(ev('S===beforeState&&R===beforeResult&&UI.hotMap===beforeHot'), true);
ev('window.compute=originalCompute');
assert.equal(ev('S.biz.length'), 0);
assert.equal(ev('S.offers.length'), 1);
assert.deepEqual(errors, []);
dom.window.close();
});
test('auto-pay rushes affordable repairs once, skips unaffordable and expired incidents, and obeys its toggle', () => {
const { ev, dom, errors } = load();
setup(ev);
ev(`S.cash=10000;S.links=[{id:'fiber',a:'fra',b:'ams',kind:'df',sys:'lite',ch:['zr4'],km:450,sub:false,ready:0,cut:0,eqDown:10,chFail:{i:0,until:10},mo:1}];
S.pops.fra.down=8;S.inc=[
{id:'amp',type:'amp',ref:'fiber',until:10,cost:30000,msg:'Broken amp'},
{id:'optic',type:'optic',ref:'fiber',until:10,cost:5000,msg:'Broken optic'},
{id:'slow',type:'crash',ref:'fra',until:8,cost:2000,slow:true,msg:'Slow boot'},
{id:'orphan',type:'amp',ref:'gone',until:10,cost:299,msg:'Removed equipment'},
{id:'expired',type:'amp',ref:'fiber',until:0,cost:1000,msg:'Expired'},
{id:'ddos',type:'ddos',ref:'fra',until:10,cost:1000,msg:'Attack'}];
S.autoRepair=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(1)`);
assert.equal(ev('S.cash'), 3000);
assert.equal(ev("S.inc.some(i=>i.id==='optic')"), false);
assert.equal(ev('S.links[0].chFail'), null);
assert.equal(ev("S.inc.find(i=>i.id==='slow').rushed"), true);
assert.equal(ev("S.inc.find(i=>i.id==='slow').until"), 1);
assert.equal(ev("S.inc.find(i=>i.id==='slow').cost"), 0);
assert.equal(ev('S.pops.fra.down'), 1);
ev('automationTick(2)');
assert.equal(ev('S.cash'), 3000, 'no duplicate rush payment');
ev('S.cash=40000;automationTick(3)');
assert.equal(ev('S.cash'), 10000);
assert.equal(ev('S.links[0].eqDown'), 0);
assert.equal(ev("S.inc.some(i=>i.id==='amp')"), false);
ev("ACT.autoToggle({k:'autoRepair'});S.inc.push({id:'new',type:'amp',ref:'fiber',until:10,cost:1000,msg:'New failure'});automationTick(4)");
assert.equal(ev('S.cash'), 10000);
assert.equal(ev("S.inc.some(i=>i.id==='new')"), true);
assert.deepEqual(errors, []);
dom.window.close();
});
test('automation pauses with the game, dialogs, hidden pages and game over', () => {
const { ev, dom, errors } = load();
setup(ev);
offer(ev, 'paused');
ev('S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;UI.speed=0;automationTick(5000)');
assert.equal(ev('S.biz.length'), 0);
ev('UI.speed=1;automationTick(9999)');
assert.equal(ev('S.biz.length'), 0, 'resume starts a fresh five-second wait');
ev("openModal('<p>Menu</p>');automationTick(10000);closeModal()");
ev("Object.defineProperty(document,'visibilityState',{configurable:true,value:'hidden'});automationTick(15000)");
ev("Object.defineProperty(document,'visibilityState',{configurable:true,value:'visible'});S.lost=true;automationTick(20000);S.lost=false;automationTick(24999)");
assert.equal(ev('S.biz.length'), 0);
ev('automationTick(25000)');
assert.equal(ev('S.biz.length'), 1);
assert.deepEqual(errors, []);
dom.window.close();
});
test('the frame loop repairs new incidents without waiting for the sales timer', () => {
const { ev, dom, errors } = load();
setup(ev);
ev(`S.autoRepair=true;S.links=[{id:'fiber',a:'fra',b:'ams',kind:'df',sys:'lite',ch:['zr4'],km:450,sub:false,ready:0,cut:0,mo:1}];
window.originalDay=dayTick;window.dayTick=()=>{S.links[0].eqDown=10;S.inc.push({id:'new',type:'amp',ref:'fiber',until:10,cost:1000,msg:'Broken amp'})};
window.cashBefore=S.cash;last=0;acc=DAY_MS;frame(16);window.dayTick=originalDay`);
assert.equal(ev('S.cash'), ev('cashBefore-1000'));
assert.equal(ev('S.inc.length'), 0);
assert.equal(ev('S.links[0].eqDown'), 0);
assert.deepEqual(errors, []);
dom.window.close();
});
test('toggles persist, old and malformed saves default off, and the timer resets for another game', () => {
const { ev, dom, errors } = load();
setup(ev);
assert.equal(ev('S.autoSales||S.autoRepair'), false);
ev("ACT.autoToggle({k:'autoSales'});ACT.autoToggle({k:'autoRepair'});save();S=migrate(JSON.parse(localStorage.getItem('sot-save-v1')))");
assert.equal(ev('S.autoSales&&S.autoRepair'), true);
ev("delete S.autoSales;delete S.autoRepair;S=migrate(S)");
assert.equal(ev('S.autoSales||S.autoRepair'), false);
ev("S.autoSales='true';S.autoRepair=1;S=migrate(S);ACT.autoToggle({k:'cash'})");
assert.equal(ev('S.autoSales||S.autoRepair'), false);
ev('UI.autoGame=S;UI.autoSalesAt=0;S=migrate(JSON.parse(JSON.stringify(S)));S.autoSales=true;compute()');
offer(ev, 'imported');
ev('automationTick(100000)');
assert.equal(ev('S.biz.length'), 0, 'an imported game does not inherit another game timer');
ev('automationTick(105000)');
assert.equal(ev('S.biz.length'), 1);
assert.deepEqual(errors, []);
dom.window.close();
});
test('both toggle buttons work by keyboard-compatible DOM events on phones in every language', () => {
for (const lang of ['en', 'it', 'pt', 'fr', 'es']) {
const { ev, dom, errors } = load(lang === 'en' ? {} : { lang });
setup(ev);
dom.window.innerWidth = 360;
for (const [tab, key] of [['deals', 'autoSales'], ['noc', 'autoRepair']]) {
ev(`ACT.leftTab({t:'${tab}'});renderAll()`);
const button = [...dom.window.document.querySelectorAll('#leftBody [data-act="autoToggle"]')].find(b => JSON.parse(b.dataset.args).k === key);
assert.ok(button, lang);
assert.equal(button.getAttribute('aria-pressed'), 'false', lang);
button.focus();
button.click();
const updated = dom.window.document.querySelector('#leftBody [data-act="autoToggle"]');
assert.equal(updated.getAttribute('aria-pressed'), 'true', lang);
assert.equal(ev(`S.${key}`), true, lang);
assert.doesNotMatch(dom.window.document.getElementById('leftBody').textContent, /automation\./, lang);
}
assert.deepEqual(errors, [], lang);
dom.window.close();
}
});