From 2a83892de80dfefe5e256699dbf1fa2fb1e8bb78 Mon Sep 17 00:00:00 2001 From: LookedPath <2457111+LookedPath@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:31:59 +0000 Subject: [PATCH] Fix subsea upgrade scheduling and add one-click construction rush --- CHANGELOG.md | 2 + package.json | 2 +- site/i18n/fr.js | 4 +- site/i18n/it.js | 4 +- site/i18n/pt.js | 4 +- site/index.html | 24 +++- tests/subsea-upgrade-timing.test.js | 187 ++++++++++++++++++++++++++++ 7 files changed, 220 insertions(+), 7 deletions(-) create mode 100644 tests/subsea-upgrade-timing.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 99f50dd..1a05322 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Rushing subsea cable construction now advances its pending terminal and optical-engineering upgrades too; construction delays keep them in step. A new one-click crew option brings ground or subsea cable construction to one day remaining for the same price as repeated hires. Extra crews stop at one day remaining instead of charging for no time saved. Loading an older save also shortens upgrades stuck with an excessive wait. + - The NOC now keeps every notification from the last 10 minutes near the top of its tab, newest first, so nothing that popped up while you looked away is lost. Each one shows its title, a short text and how long ago it happened, repeats fold into one line with a count, and an Open button takes you to the city, link, customer, bank or goal it is about. The NOC button in the top bar and the NOC tab on phones count the ones you have not read yet. Resolved incidents now say what was fixed and where. - Peering now comes with an inbox: every IX port brings peering requests from networks you have never heard of, and sessions drop when someone blows past the max-prefix limit their PeeringDB promised. Answer requests, decide whether a max-prefix alert is growth or a route leak, and keep your reputation up, because selective networks hear when you never answer. For $20M a year the Large Peering Model AI answers it all for you, quickly and often wrongly. - PNIs take time: a cross-connect with a small network takes a few weeks, and the big content networks, Tier 1s and big eyeball networks quote 6 to 12 months for a new PNI or an augment. The content networks and Tier 1s no longer do 10G PNIs (100G and up), Doitsche Telekomm still sells 1G, and Microsnoft has no capacity on the US east coast at all. diff --git a/package.json b/package.json index d09f328..edee055 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "url": "git+https://github.com/fjaeckel/seriesoftubes.git" }, "scripts": { - "test": "node --test --test-concurrency=1 tests/game.test.js tests/build.test.js tests/persist.test.js tests/services.test.js tests/peering.test.js tests/inbox.test.js tests/issues.test.js tests/regions.test.js tests/modes.test.js tests/levels.test.js tests/speed.test.js tests/i18n.test.js tests/routing-reference.test.js tests/perf.test.js tests/sea-routing.test.js", + "test": "node --test --test-concurrency=1 tests/game.test.js tests/build.test.js tests/persist.test.js tests/services.test.js tests/peering.test.js tests/inbox.test.js tests/issues.test.js tests/regions.test.js tests/modes.test.js tests/levels.test.js tests/speed.test.js tests/i18n.test.js tests/routing-reference.test.js tests/perf.test.js tests/sea-routing.test.js tests/subsea-upgrade-timing.test.js", "build": "bash scripts/build.sh", "i18n:check": "node scripts/i18n-check.js", "serve": "npm run build && npx --yes serve@14.2.4 _site", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 6b96ec0..ead8a64 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -1289,7 +1289,6 @@ "Dark fiber IRU signed.
{a}–{b} will be spliced and handed over in about 30 days.":"IRU de fibre noire signé.
{a}–{b} sera soudée et livrée dans environ 30 jours.", "Can't add {optic}.
{why}":"Impossible d’ajouter {optic}.
{why}", "Line system swap
All channels are dark for a day while the ROADMs go in.":"Changement de système de ligne
Tous les canaux sont éteints pendant une journée, le temps de poser les ROADM.", -"More crews on site.
Construction is 30 days ahead.":"Plus d’équipes sur le chantier.
Les travaux ont 30 jours d’avance.", "Generator!":"Groupe électrogène !", "Start {name}?":"Lancer {name} ?", "{name} will be replaced. Export it from the menu first if you want to keep it.":"{name} sera remplacé. Exporte-le d’abord depuis le menu si tu veux le garder.", @@ -2825,4 +2824,7 @@ "Show all {n}":"Tout afficher ({n})", "Resolved: {what}
{where} is back to normal.":"Résolu : {what}
{where} est revenu à la normale.", "Resolved: {what}":"Résolu : {what}", +"Finish in 1 day {price}":"Terminer en 1 jour {price}", +"More crews on site.
Construction is {n} days ahead.":"Des équipes en renfort.
Les travaux ont {n} jours d’avance.", +"More crews on site.
Construction is {n} day ahead.":"Des équipes en renfort.
Les travaux ont {n} jour d’avance.", }; diff --git a/site/i18n/it.js b/site/i18n/it.js index e797889..9ddafe9 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -1288,7 +1288,6 @@ "Dark fiber IRU signed.
{a}–{b} will be spliced and handed over in about 30 days.":"IRU di dark fiber firmato.
{a}–{b} sarà giuntata e consegnata in circa 30 giorni.", "Can't add {optic}.
{why}":"Impossibile aggiungere {optic}.
{why}", "Line system swap
All channels are dark for a day while the ROADMs go in.":"Cambio del line system
Tutti i canali restano spenti per un giorno mentre si installano i ROADM.", -"More crews on site.
Construction is 30 days ahead.":"Più squadre in cantiere.
I lavori sono avanti di 30 giorni.", "Generator!":"Generatore!", "Start {name}?":"Vuoi iniziare {name}?", "{name} will be replaced. Export it from the menu first if you want to keep it.":"La partita con {name} verrà sostituita. Se vuoi tenerla, prima esportala dal menu.", @@ -2825,4 +2824,7 @@ "Show all {n}":"Mostra tutte e {n}", "Resolved: {what}
{where} is back to normal.":"Risolto: {what}
{where} è tornato alla normalità.", "Resolved: {what}":"Risolto: {what}", +"Finish in 1 day {price}":"Termina in 1 giorno {price}", +"More crews on site.
Construction is {n} days ahead.":"Più squadre sul posto.
I lavori sono in anticipo di {n} giorni.", +"More crews on site.
Construction is {n} day ahead.":"Più squadre sul posto.
I lavori sono in anticipo di {n} giorno.", }; diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 1065f74..3fc4c81 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -1287,7 +1287,6 @@ "Dark fiber IRU signed.
{a}–{b} will be spliced and handed over in about 30 days.":"IRU de dark fiber assinado.
{a}–{b} será emendada e entregue em uns 30 dias.", "Can't add {optic}.
{why}":"Não dá para adicionar {optic}.
{why}", "Line system swap
All channels are dark for a day while the ROADMs go in.":"Troca do line system
Todos os canais ficam apagados por um dia enquanto os ROADMs são instalados.", -"More crews on site.
Construction is 30 days ahead.":"Mais equipes na obra.
A construção está 30 dias adiantada.", "Generator!":"Gerador!", "Start {name}?":"Começar {name}?", "{name} will be replaced. Export it from the menu first if you want to keep it.":"{name} será substituído. Exporte pelo menu antes se quiser guardar.", @@ -2825,4 +2824,7 @@ "Show all {n}":"Mostrar todas as {n}", "Resolved: {what}
{where} is back to normal.":"Resolvido: {what}
{where} voltou ao normal.", "Resolved: {what}":"Resolvido: {what}", +"Finish in 1 day {price}":"Concluir em 1 dia {price}", +"More crews on site.
Construction is {n} days ahead.":"Mais equipes no local.
A construção está {n} dias adiantada.", +"More crews on site.
Construction is {n} day ahead.":"Mais equipes no local.
A construção está {n} dia adiantada.", }; diff --git a/site/index.html b/site/index.html index 2f853f0..efb0ec9 100644 --- a/site/index.html +++ b/site/index.html @@ -743,6 +743,23 @@ const SUB_MAXKM=()=>subReach(1,1); const SUB_UPGRADES={terminal:{n:N_('Premium submarine terminals'),cost:5000000,days:30},engineering:{n:N_('Optical engineering'),cost:12000000,days:180}}; const subUpgradeReady=(l,k)=>l.kind==='df'&&l.sub&&l.own&&Number.isFinite(l['sub'+k])&&l['sub'+k]<=S.day; const subUpgradeCost=(l,k)=>SUB_UPGRADES[k].cost+(k==='engineering'?Math.round(l.km*1000):0); +// Pending transmission work follows the construction schedule. Keep the actual +// shift (the last crew purchase can save fewer than 30 days) and completed work. +function setCableReady(l,ready,day=S.day){const shift=ready-l.ready; + if(l.kind==='df'&&l.own&&l.sub)for(const k of Object.keys(SUB_UPGRADES)){ + const f='sub'+k;if(Number.isFinite(l[f])&&l[f]>day)l[f]=Math.max(day+1,l[f]+shift); + }l.ready=ready; +} +const crewCost=l=>Math.round(15000+l.km*6); +const crewSteps=l=>Math.max(0,Math.ceil((l.ready-S.day-1)/30)); +// Old saves lack purchase dates. Only shorten dates beyond any valid remaining +// commissioning window. Credit elapsed time since the actual cable finish; +// recent purchases and installed upgrades stay untouched. +function repairSubUpgradeDates(l,day){if(l.kind!=='df'||!l.own||!l.sub)return; + for(const [k,U] of Object.entries(SUB_UPGRADES)){const f='sub'+k; + if(Number.isFinite(l[f])&&l[f]>Math.max(day,l.ready)+U.days)l[f]=l.ready+U.days; + } +} function optModes(o,l){return (OPT[o].modes||[[OPT[o].g,OPT[o].reach]]).map(([g,r])=>{ let reach=reachOn(r,l.sub); if(l.sub&&['tp16','tp32'].includes(o)&&g<=1200){ @@ -2387,6 +2404,7 @@ function sanitize(s){ if(!isCity(s.home))s.home=Object.keys(s.pops)[0]||'fra'; const tier=v=>int(v,0,PORT.length-1,0),lag=v=>int(v,1,LAG_MAX,1),sid=v=>String(v==null?uid():v).slice(0,40); s.links=s.links.filter(l=>l&&isCity(l.a)&&isCity(l.b)&&l.a!==l.b).map(l=>{l.id=sid(l.id);l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);if(l.pairs!==undefined)l.pairs=Math.min(l.sub?SUB_PAIRS_MAX:s.lvl>=PAIRS_LV?PAIRS_BIG:PAIRS_MAX,Math.max(1,Math.floor(+l.pairs)||1));if(l.kind!=='df'&&l.kind!=='vxc')l.kind='wave';if(l.kind==='wave')l.tier=int(l.tier,0,LT.length-1,0);if(l.cable&&!own(CAB,l.cable))l.cable=null;if(l.kind==='vxc'&&!own(VXC,l.vt))l.vt=0;if(l.kind==='df'){if(!own(DF_SYS,l.sys))l.sys='lite';l.ch=Array.isArray(l.ch)?l.ch.filter(o=>own(OPT,o)):[];l.ready=num(l.ready,0);for(const k of Object.keys(SUB_UPGRADES)){const f='sub'+k;if(l[f]!==undefined){if(l.own&&l.sub&&Number.isFinite(l[f])&&l[f]>=0)l[f]=Math.round(l[f]);else delete l[f];}}if(l.seaPath!==undefined){if(l.own&&l.sub&&Array.isArray(l.seaPath)&&l.seaPath.length>=2&&l.seaPath.length<=2048&&l.seaPath.every(p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite)&&Math.abs(p[0])<=180&&Math.abs(p[1])<=90))l.seaPath=l.seaPath.map(p=>p.slice());else delete l.seaPath;}if(l.paid!==undefined){if(l.own&&l.sub&&Number.isFinite(l.paid)&&l.paid>=0)l.paid=Math.round(l.paid);else delete l.paid;}if(l.own&&l.sub&&!own(SEA_DESIGNS,l.seaDesign))l.seaDesign='standard';l.regen=int(l.regen,0,REGEN_MAX,0);}const deg=v=>v&&typeof v==='object'?{until:num(v.until,0),f:Math.min(1,Math.max(0,num(v.f,1)))}:null;if(l.loss)l.loss=deg(l.loss);if(l.metric&&!own(MET,l.metric))l.metric='normal';return l;}); + for(const l of s.links)repairSubUpgradeDates(l,s.day); const degO=v=>v&&typeof v==='object'?{until:num(v.until,0),f:Math.min(1,Math.max(0,num(v.f,1)))}:null; s.transit=s.transit.filter(t=>t&&isCity(t.city)&&isNet(t.net)).map(t=>(t.lacp=degO(t.lacp),t.site=['a','b','ab'].includes(t.site)?t.site:'a',t.id=sid(t.id),t.tier=tier(t.tier),t.n=lag(t.n),t.down=num(t.down,0),t.clean=!!t.clean,t)); s.pni=s.pni.filter(x=>x&&isCity(x.city)&&isNet(x.net)).map(x=>(x.lacp=degO(x.lacp),x.site=['a','b','ab'].includes(x.site)?x.site:'a',x.id=sid(x.id),x.tier=tier(x.tier),x.n=lag(x.n),x.sacrif=!!x.sacrif,x)); @@ -2924,7 +2942,7 @@ function dayTick(){ {const top=custLevel();if(top>(S.lvl||1)){for(let lv=(S.lvl||1)+1;lv<=top;lv++){track('level_'+lv);toast(tr('Customer level {lv}: {name}
New customers unlocked: {unlock}',{lv,name:LEVELS[lv-1].n,unlock:LEVELS[lv-1].unlock})+`
${esc(LEVELS[lv-1].q)}`,'goal');}S.lvl=top;sfx('coin');}} for(const l of S.links){if(l.kind!=='df')continue; if(l.ready===d){toast(`${l.own?tr('Your fiber is finished: {a}–{b}',{a:CITY[l.a].name,b:CITY[l.b].name}):tr('Dark fiber handed over: {a}–{b}',{a:CITY[l.a].name,b:CITY[l.b].name})}
${(l.ch||[]).length?tr('Channels are lighting up now.'):tr('It is dark. Add optics to light it up.')}`,'goal',[{l:tr('Open'),act:'selLink',args:{id:l.id}}]);sfx('coin');} - if(l.own&&l.ready>d&&Math.random()<0.012){const extra=10+Math.floor(Math.random()*40);l.ready+=extra;toast(tr('Construction delay: +{n} days
{why} ({a}–{b})',{n:extra,why:pick(l.sub?SEA_DELAYS.map(x=>tr(x)):[tr('Archaeologists found a Roman bathhouse on your route.'),tr('A protected hamster species lives along the right-of-way.'),tr('The railway changed its mind about the easement.'),tr('The drilling crew hit a granite boulder the size of a bus.'),tr('A town council wants a public hearing. About the color of the manhole covers.'),tr('Somebody else’s gas main was exactly where the map said it was not.'),tr('The permit office lost your permit. And then the replacement.')]),a:CITY[l.a].name,b:CITY[l.b].name}),'bad');}} + if(l.own&&l.ready>d&&Math.random()<0.012){const extra=10+Math.floor(Math.random()*40);setCableReady(l,l.ready+extra);toast(tr('Construction delay: +{n} days
{why} ({a}–{b})',{n:extra,why:pick(l.sub?SEA_DELAYS.map(x=>tr(x)):[tr('Archaeologists found a Roman bathhouse on your route.'),tr('A protected hamster species lives along the right-of-way.'),tr('The railway changed its mind about the easement.'),tr('The drilling crew hit a granite boulder the size of a bus.'),tr('A town council wants a public hearing. About the color of the manhole covers.'),tr('Somebody else’s gas main was exactly where the map said it was not.'),tr('The permit office lost your permit. And then the replacement.')]),a:CITY[l.a].name,b:CITY[l.b].name}),'bad');}} // DDoS protection SLA: if a protected customer's own city is hit and still goes down, you pay out (once per attack). if(S.ev.ddos&&S.ev.ddos.until>d){const a=S.ev.ddos; for(const b of S.biz)if(b.type==='scrub'&&b.city===a.city&&b.slaFor!==a.start&&sfOf(R,b.city)<0.85){ @@ -3335,7 +3353,7 @@ const ACT={ addPair:({id})=>{const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||!l.own||!isRdm(l.sys)||l.ready>S.day)return;const n=Math.max(1,l.pairs|0);if(n>=pairsMax(l))return;if((l.ch||[]).length+soldSlots(l)Fill this pair first.
Light all {max} channels before you light another fiber pair.',{max:chMax(l)}),'bad');sfx('err');return;}if(!spend(pairCost(l)))return;l.pairs=n+1;toast(tr('Fiber pair {n} is lit: {a}–{b}.
Another ROADMaster 9000 and a fresh chain of amplifiers. Room for {m} more channels.',{n:n+1,a:CITY[l.a].name,b:CITY[l.b].name,m:DF_SYS[l.sys].max}),'good');sfx('build');after();}, upSys:({id})=>{const l=S.links.find(x=>x.id===id),to=l&&sysNext(l);if(!to||DF_SYS[to].lvl>lvl())return;if(!spend(sysUpCost(l)))return;l.sys=to;if(l.ready<=S.day){l.eqDown=S.day+1;toast(tr('Line system swap
All channels are dark for a day while the ROADMs go in.'),'bad');}after();}, spares:({id})=>{const l=S.links.find(x=>x.id===id);if(!l)return;l.spares=!l.spares;sfx('click');after();}, - crews:({id})=>{const l=S.links.find(x=>x.id===id);if(!l||l.ready<=S.day)return;const c=Math.round(15000+l.km*6);if(!spend(c))return;l.ready=Math.max(S.day+1,l.ready-30);toast(tr('More crews on site.
Construction is 30 days ahead.'),'good');after();}, + crews:({id,all})=>{const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||!l.own||l.ready<=S.day+1)return;const n=all?crewSteps(l):1,c=n*crewCost(l);if(!spend(c))return;const ready=Math.max(S.day+1,l.ready-30*n),saved=l.ready-ready;setCableReady(l,ready);toast(trn('More crews on site.
Construction is {n} day ahead.','More crews on site.
Construction is {n} days ahead.',saved,{n:saved}),'good');after();}, addGen:({city})=>{const p=S.pops[city];if(!p||p.gen)return;if(!spend(GEN_COST))return;p.gen=true;floater(CITY[city].x,CITY[city].y-30,tr('Generator!'),'#FF8A3D');after();}, randomName:()=>{const input=$('nmIn');if(input)input.value=UI.nm=randomNetworkName(input.value);}, start:()=>{const nm=(($('nmIn')&&$('nmIn').value)||randomNetworkName()).slice(0,24);beginGame(nm,UI.startCity,{mode:UI.mode==='sandbox'?'sandbox':'normal'});}, @@ -3800,7 +3818,7 @@ function dfPanel(l){ const load=R.load[l.id]||0,cap=dfCap(l),u=cap?load/cap:0,bld=l.ready>S.day,A=CITY[l.a].name,B=CITY[l.b].name,inc=S.inc.find(i=>i.ref===l.id||i.ref===(l.trench||l.id)),amps=ampCount(l.km),sysD=DF_SYS[l.sys]; let h=`
${tr('Dark fiber · {kind} · {km} km',{kind:l.own?tr('your own build'):tr('leased IRU'),km:l.km.toLocaleString()})}

${A} ⇄ ${B}

`; if(bld){const tot=Math.max(1,l.ready-l.day),done=clamp((S.day-l.day)/tot,0,1); - h+=`

${l.own?tr('Under construction'):tr('Being spliced')}

${l.own?tr('Permits, trenching, splicing'):tr('IRU handover')}${tr('{n} days left',{n:l.ready-S.day})}
${l.own?btn(tr('Hire extra crews {price} · −30 days',{price:fmt$(Math.round(15000+l.km*6))}),'crews',{id:l.id},'sm',S.cash<15000+l.km*6):''}

${tr("You can pre-install optics now so it lights up the day it's ready.")}

`;} + h+=`

${l.own?tr('Under construction'):tr('Being spliced')}

${l.own?tr('Permits, trenching, splicing'):tr('IRU handover')}${tr('{n} days left',{n:l.ready-S.day})}
${l.own?`
${btn(tr('Hire extra crews {price} · −30 days',{price:fmt$(crewCost(l))}),'crews',{id:l.id},'sm',l.ready<=S.day+1||S.cash{price}',{price:fmt$(crewSteps(l)*crewCost(l))}),'crews',{id:l.id,all:1},'sm',!crewSteps(l)||S.cash`:''}

${tr("You can pre-install optics now so it lights up the day it's ready.")}

`;} else if(inc&&linkDown(l))h+=`

${tr('Dark!')}

${esc(inc.msg)}

${inc.cost?btn(`${esc(inc.fix||tr('Rush repair'))} ${fmt$(inc.cost)}`,'fixInc',{id:inc.id},'red',S.cash`; h+=`

${tr('Capacity')}

${tr('{n} of {max} channels lit',{n:(l.ch||[]).length,max:chMax(l)})}${soldSlots(l)?` · ${tr('{n} sold as alien waves',{n:soldSlots(l)})}`:''}${fmtG(load)} / ${fmtG(cap)}
${l.own&&l.sub?`
${tr('Cable design')}${tr((SEA_DESIGNS[l.seaDesign]||SEA_DESIGNS.standard).n)}
`:''} diff --git a/tests/subsea-upgrade-timing.test.js b/tests/subsea-upgrade-timing.test.js new file mode 100644 index 0000000..d2d6a55 --- /dev/null +++ b/tests/subsea-upgrade-timing.test.js @@ -0,0 +1,187 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +function setup(ev) { + ev(`ACT.start({});S.cash=1e11;S.lvl=13;S.day=100;for(const g of GOALS)S.done[g.id]=0; + S.links=[{id:'cable',a:'lag',b:'bde',kind:'df',own:true,sub:true,sys:'roadm',km:7000,ch:[],day:100,ready:1000,cut:0,mo:1}];`); +} + +function dates(ev) { + return JSON.parse(ev('JSON.stringify([S.links[0].ready,S.links[0].subterminal,S.links[0].subengineering])')); +} + +test('upgrades queued during construction follow crews and keep their 30/180-day commissioning time', () => { + const { ev, dom, errors } = load(); + try { + setup(ev); + ev("ACT.subUpgrade({id:'cable',k:'terminal'});ACT.subUpgrade({id:'cable',k:'engineering'})"); + assert.deepEqual(dates(ev), [1000, 1030, 1180]); + const paid = ev('S.links[0].paid'); + ev("ACT.crews({id:'cable'})"); + assert.deepEqual(dates(ev), [970, 1000, 1150]); + ev("for(let i=0;i<29;i++)ACT.crews({id:'cable'})"); + assert.deepEqual(dates(ev), [101, 131, 281], 'last crew purchase shifts dates by 29 days, not 30'); + const cash = ev('S.cash'); + ev("ACT.crews({id:'cable'})"); + assert.equal(ev('S.cash'), cash, 'one day remaining: crews cannot charge for saving zero days'); + assert.deepEqual(dates(ev), [101, 131, 281], 'commissioning cannot be rushed further through the cable'); + ev("UI.sel={type:'link',id:'cable'};renderPanel()"); + assert.equal(dom.window.document.querySelector('#panelBody [data-act=crews]').disabled, true); + assert.equal(ev('S.links[0].paid'), paid, 'no second upgrade charge'); + ev('S=migrate(JSON.parse(JSON.stringify(S)))'); + assert.deepEqual(dates(ev), [101, 131, 281], 'save round trip preserves commissioning windows'); + ev('S.day=130');assert.equal(ev("subUpgradeReady(S.links[0],'terminal')"), false); + ev('S.day=131');assert.equal(ev("subUpgradeReady(S.links[0],'terminal')"), true); + ev('S.day=280');assert.equal(ev("subUpgradeReady(S.links[0],'engineering')"), false); + ev('S.day=281');assert.equal(ev("subUpgradeReady(S.links[0],'engineering')"), true); + assert.deepEqual(errors, []); + } finally { dom.window.close(); } +}); + +test('ordering upgrades early is as fast as ordering after rushing the cable', () => { + const { ev, dom } = load(); + try { + setup(ev); + ev("ACT.subUpgrade({id:'cable',k:'terminal'});ACT.subUpgrade({id:'cable',k:'engineering'});for(let i=0;i<30;i++)ACT.crews({id:'cable'})"); + const early = dates(ev); + setup(ev); + ev("for(let i=0;i<30;i++)ACT.crews({id:'cable'});S.day=101;ACT.subUpgrade({id:'cable',k:'terminal'});ACT.subUpgrade({id:'cable',k:'engineering'})"); + assert.deepEqual(dates(ev), early); + } finally { dom.window.close(); } +}); + +test('packages included in the original order stay aligned with its accelerated finish', () => { + const { ev, dom } = load(); + try { + setup(ev); + ev("S.won=true;UI.pending={a:'lag',b:'bde'};UI.seaterminal=UI.seaengineering=true;ACT.orderCable();S.links=[S.links.at(-1)]"); + assert.equal(ev('S.links[0].subterminal'), ev('S.links[0].ready')); + assert.equal(ev('S.links[0].subengineering'), ev('S.links[0].ready')); + ev("ACT.crews({id:S.links[0].id})"); + assert.equal(ev('S.links[0].subterminal'), ev('S.links[0].ready')); + assert.equal(ev('S.links[0].subengineering'), ev('S.links[0].ready')); + ev('S=migrate(JSON.parse(JSON.stringify(S)))'); + assert.equal(ev('S.links[0].subengineering'), ev('S.links[0].ready')); + } finally { dom.window.close(); } +}); + +test('construction delays move pending commissioning dates without reinstalling completed equipment', () => { + const { ev, dom } = load(); + try { + setup(ev); + ev(`ACT.subUpgrade({id:'cable',k:'engineering'});S.links[0].subterminal=80; + // Force the actual construction-delay event, and keep all other randomness harmless. + S.nextFail=S.nextEvent=1e8;Math.random=()=>0;dayTick();`); + assert.deepEqual(dates(ev), [1010, 80, 1190]); + assert.equal(ev("subUpgradeReady(S.links[0],'terminal')"), true); + } finally { dom.window.close(); } +}); + +test('old saves repair excessive pending waits without changing valid dates, charges or installed upgrades', () => { + const { ev, dom } = load(); + try { + setup(ev); + ev(`const incoming=JSON.parse(JSON.stringify(S));incoming.day=500;const template=incoming.links[0];incoming.links=[ + {...template,id:'finished',ready:101,subterminal:1030,subengineering:1180,paid:8e7}, + {...template,id:'building',ready:600,subterminal:1030,subengineering:1180}, + {...template,id:'recently-finished',ready:490,subterminal:1030,subengineering:1180}, + {...template,id:'recent',ready:101,subterminal:520,subengineering:650}, + {...template,id:'installed',ready:101,subterminal:80,subengineering:400}, + {...template,id:'bundled',ready:600,subterminal:600,subengineering:600}, + {...template,id:'bare',ready:101} + ];S=migrate(incoming);`); + const result = JSON.parse(ev('JSON.stringify(S.links.map(l=>[l.subterminal,l.subengineering]))')); + assert.deepEqual(result, [[131, 281], [630, 780], [520, 670], [520, 650], [80, 400], [600, 600], [null, null]]); + assert.equal(ev('S.links[0].paid'), 8e7); + assert.equal(ev('S.links[0].ready'), 101); + assert.equal(ev("subUpgradeReady(S.links[0],'terminal')&&subUpgradeReady(S.links[0],'engineering')"), true, 'elapsed commissioning time is credited'); + ev('S=migrate(JSON.parse(JSON.stringify(S)))'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.links.map(l=>[l.subterminal,l.subengineering]))')), result, 'loading again does not restart or shorten legitimate timers'); + ev('S.day=510;S=migrate(JSON.parse(JSON.stringify(S)))'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.links.map(l=>[l.subterminal,l.subengineering]))')), result, 'elapsed repair time is retained'); + } finally { dom.window.close(); } +}); + +test('land fiber, leased cables, invalid upgrades and rejected crew purchases remain unaffected', () => { + const { ev, dom } = load(); + try { + setup(ev); + ev("S.links[0].subterminal=1030;S.links[0].subengineering=1180;S.cash=0;ACT.crews({id:'cable'})"); + assert.deepEqual(dates(ev), [1000, 1030, 1180]); + ev(`S.links.push({...S.links[0],id:'land',sub:false},{...S.links[0],id:'leased',own:false}); + setCableReady(S.links[1],970);setCableReady(S.links[2],970);`); + assert.equal(ev('S.links[1].subterminal'), 1030); + assert.equal(ev('S.links[2].subengineering'), 1180); + ev("S.links[0].subterminal='soon';S.links[0].subengineering=-1;S=sanitize(S)"); + assert.equal(ev('S.links[0].subterminal'), undefined); + assert.equal(ev('S.links[0].subengineering'), undefined); + assert.equal(ev('S.links[1].subterminal'), undefined); + assert.equal(ev('S.links[2].subengineering'), undefined); + } finally { dom.window.close(); } +}); + +test('one-click completion costs the same as repeated crew hires and advances pending upgrades identically', () => { + const { ev, dom, errors } = load(); + try { + setup(ev); + ev("ACT.subUpgrade({id:'cable',k:'terminal'});ACT.subUpgrade({id:'cable',k:'engineering'});UI.sel={type:'link',id:'cable'};renderPanel()"); + const button = [...dom.window.document.querySelectorAll('#panelBody [data-act=crews]')].find(b => JSON.parse(b.dataset.args).all); + assert.ok(button && !button.disabled, 'one-click option is available'); + const cash = ev('S.cash'); + assert.ok(button.textContent.includes(ev('fmt$(30*Math.round(15000+7000*6))')), 'full price is shown before purchase'); + button.click(); + const bulkDates = dates(ev), bulkCash = ev('S.cash'); + assert.deepEqual(bulkDates, [101, 131, 281]); + assert.equal(cash - bulkCash, 30 * 57000); + const after = [...dom.window.document.querySelectorAll('#panelBody [data-act=crews]')]; + assert.ok(after.every(b => b.disabled), 'both options stop at one day'); + ev("ACT.crews({id:'cable',all:1})"); + assert.equal(ev('S.cash'), bulkCash, 'repeat submission cannot charge again'); + setup(ev); + ev("ACT.subUpgrade({id:'cable',k:'terminal'});ACT.subUpgrade({id:'cable',k:'engineering'});for(let i=0;i<30;i++)ACT.crews({id:'cable'})"); + assert.deepEqual(dates(ev), bulkDates); + assert.equal(ev('S.cash'), bulkCash); + assert.deepEqual(errors, []); + } finally { dom.window.close(); } +}); + +test('one-click completion is atomic when unaffordable and handles short or completed construction', () => { + const { ev, dom } = load(); + try { + setup(ev); + ev("S.cash=30*57000-1;UI.sel={type:'link',id:'cable'};renderPanel()"); + const bulk = [...dom.window.document.querySelectorAll('#panelBody [data-act=crews]')].find(b => JSON.parse(b.dataset.args).all); + assert.equal(bulk.disabled, true); + ev("ACT.crews({id:'cable',all:1})"); + assert.equal(ev('S.cash'), 30 * 57000 - 1); + assert.equal(ev('S.links[0].ready'), 1000, 'no partial purchase'); + ev("S.cash=57000;S.links[0].ready=102;ACT.crews({id:'cable',all:1})"); + assert.equal(ev('S.cash'), 0); + assert.equal(ev('S.links[0].ready'), 101, 'two days remaining costs one normal hire'); + assert.match(dom.window.document.body.textContent, /Construction is 1 day ahead\./); + ev("S.cash=57000;S.day=101;ACT.crews({id:'cable',all:1})"); + assert.equal(ev('S.cash'), 57000, 'completed construction cannot be rushed'); + ev("S.day=100;S.links[0].ready=1000;S.links[0].own=false;ACT.crews({id:'cable',all:1})"); + assert.equal(ev('S.links[0].ready'), 1000, 'leased handovers cannot buy construction crews'); + } finally { dom.window.close(); } +}); + +test('owned ground fiber exposes the one-click button and uses the same crew pricing', () => { + const { ev, dom, errors } = load(); + try { + setup(ev); + ev("ACT.buildPop({city:'ams'});Object.assign(S.links[0],{a:'fra',b:'ams',sub:false,km:800,ready:191});UI.sel={type:'link',id:'cable'};renderPanel()"); + const bulk = [...dom.window.document.querySelectorAll('#panelBody [data-act=crews]')].find(b => JSON.parse(b.dataset.args).all); + assert.ok(bulk && !bulk.disabled, 'ground construction has the same one-click control'); + assert.ok(bulk.textContent.includes(ev('fmt$(3*(15000+800*6))')), '91 days remaining requires three hires'); + const cash = ev('S.cash'); + bulk.click(); + assert.equal(ev('S.links[0].ready'), 101); + assert.equal(cash - ev('S.cash'), 59400); + assert.equal(ev('S.links[0].subterminal'), undefined); + assert.equal(ev('S.links[0].subengineering'), undefined); + assert.ok([...dom.window.document.querySelectorAll('#panelBody [data-act=crews]')].every(b => b.disabled)); + assert.deepEqual(errors, []); + } finally { dom.window.close(); } +});