From 4932b3f93a786fb29c574a374d9eebf65ceecfec Mon Sep 17 00:00:00 2001 From: logfro Date: Wed, 28 Oct 2026 01:44:17 +0100 Subject: [PATCH] Add bulk PNI ordering across networks and POPs Add two actions to the NOC Traffic tab: - Order PNIs with one network at every shared POP. - Order PNIs with all eligible networks at every shared POP, including long-tail peers. Both actions offer a selectable port size and preview new connections, upgrades, total setup costs, additional monthly charges and blocked sites. Upgrade smaller PNIs while preserving larger connections, pending orders and existing LAG members. Reserve router capacity across the batch and account for pending speed and LAG augments to avoid overbooking ports. Require the full setup budget before placing any orders. Reuse normal peering policies, minimum port sizes and provisioning delays, then recompute and save once for the entire batch. Keep large global previews compact with collapsible network and blocked-connection lists. Translate the new UI into all five supported languages and add tests for single-network and global ordering, capacity, budgets, repeated clicks, save migration, and mobile keyboard interaction. Validation: - Build and translation checks pass. - 308 of 309 tests pass. The existing subsea reach test also fails on origin/main because the Windows locale uses a dot as the thousands separator where the assertion expects a comma. - Chromium desktop and phone checks pass with the supplied save. - Big-network benchmark against origin/main: dashboard tabs take 16.8 -> 17.6 ms on desktop and 77.1 -> 80.7 ms on a simulated phone (median of 15 runs). Routing results are identical, with no slowdowns beyond the benchmark's noise threshold. --- CHANGELOG.md | 2 + site/i18n/es.js | 20 +++ site/i18n/fr.js | 20 +++ site/i18n/it.js | 20 +++ site/i18n/pt.js | 20 +++ src/game/70-rules/35-pni-orders.js | 23 +++ .../90-actions/40-sites-peering-caches.js | 12 +- src/game/94-dashboard/60-dashboard.js | 3 +- src/game/95-modals/35-pni-all.js | 19 +++ src/i18n/en.js | 20 +++ tests/pni-all.test.js | 155 ++++++++++++++++++ tests/pni-global.test.js | 135 +++++++++++++++ 12 files changed, 442 insertions(+), 7 deletions(-) create mode 100644 src/game/70-rules/35-pni-orders.js create mode 100644 src/game/95-modals/35-pni-all.js create mode 100644 tests/pni-all.test.js create mode 100644 tests/pni-global.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 0094b5d..40263ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- 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. + ## [1.35.0] — 2026-10-27 - Series of Tubes now speaks Spanish. The game follows your browser's language the first time, and you can switch to Spanish under Settings or on the title screen. diff --git a/site/i18n/es.js b/site/i18n/es.js index 16f2a3c..06a16dd 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2581,6 +2581,26 @@ "peering_policy.tried_a_remote_peer_once_it":"Probaron un peer remoto una vez. Osciló durante un lanzamiento de producto. Nunca más.", "pitcairn.uk_grant_mo":"Subvención británica {mo}/mes", "pitcairn.uk_grant_mo_once_islanders":"Subvención británica {mo}/mes cuando los isleños estén en línea", +"pni_all.additional_per_month":"Coste mensual adicional", +"pni_all.all_at_port":"Peering con todas las redes · {port}", +"pni_all.delivery_and_traffic_charges":"Los plazos de entrega varían según la red. También se aplican cargos de peering basados en el tráfico cuando corresponda.", +"pni_all.n_blocked_connections":{"one":"{n} conexión no disponible","other":"{n} conexiones no disponibles"}, +"pni_all.n_blocked_pops":{"one":"{n} POP no disponible","other":"{n} POP no disponibles"}, +"pni_all.n_existing_or_pending_unchanged":{"one":"{n} PNI existente o pedido pendiente se mantiene sin cambios.","other":"{n} PNI existentes o pedidos pendientes se mantienen sin cambios."}, +"pni_all.n_networks":{"one":"{n} red","other":"{n} redes"}, +"pni_all.n_of_total_connections":"{n} / {total} conexiones", +"pni_all.n_of_total_pops":"{n} / {total} POP en común", +"pni_all.n_orders_with_net":{"one":"{n} pedido de PNI realizado con {net}. Sin cambios: {kept}; no disponibles: {blocked}.","other":"{n} pedidos de PNI realizados con {net}. Sin cambios: {kept}; no disponibles: {blocked}."}, +"pni_all.new_and_upgrades":"Nuevos: {fresh} · Ampliaciones: {up}", +"pni_all.no_shared_locations":"No hay POP en común disponibles.", +"pni_all.no_shared_pops":"No tienes POP en común con esta red.", +"pni_all.order_missing_and_upgrade_smaller":"Pide los PNI que faltan y amplía los más pequeños en los POP en común. Los PNI mayores y los pedidos pendientes se mantienen sin cambios. Se omiten los POP no disponibles.", +"pni_all.peer_all_networks":"Peering con todas las redes en todos los POP", +"pni_all.peer_at_port":"Peering en todos los POP · {port}", +"pni_all.peer_on_all_pops":"Peering en todos los POP", +"pni_all.pni_size":"Capacidad del PNI", +"pni_all.setup_total":"Coste total de instalación", +"pni_all.traffic_charges_apply":"También se aplican cargos de tráfico de {price} por Gbps.", "pnis.a_new_region_is_coming_online":"Pronto se pondrá en marcha una región nueva. Lleva poniéndose en marcha pronto desde 2019.", "pnis.about_n_days_to_go_nothing":"Faltan unos {n} días. No queda más que esperar, o perseguirlo.", "pnis.augment_with_net_delivered_in_city":"Ampliación con {net} entregada en {city}.
Ahora {port}.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 4e674bf..882a336 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2581,6 +2581,26 @@ "peering_policy.tried_a_remote_peer_once_it":"Ils ont essayé un peer distant, une fois. Il a flappé pendant un lancement de produit. Plus jamais.", "pitcairn.uk_grant_mo":"Subvention britannique {mo}/mois", "pitcairn.uk_grant_mo_once_islanders":"Subvention britannique {mo}/mois une fois les insulaires en ligne", +"pni_all.additional_per_month":"Coût mensuel supplémentaire", +"pni_all.all_at_port":"Peering avec tous les réseaux · {port}", +"pni_all.delivery_and_traffic_charges":"Les délais de livraison varient selon le réseau. Des frais de peering liés au trafic s'appliquent aussi lorsque le réseau l'exige.", +"pni_all.n_blocked_connections":{"one":"{n} connexion indisponible","other":"{n} connexions indisponibles"}, +"pni_all.n_blocked_pops":{"one":"{n} POP indisponible","other":"{n} POP indisponibles"}, +"pni_all.n_existing_or_pending_unchanged":{"one":"{n} PNI existant ou commande en attente reste inchangé.","other":"{n} PNI existants ou commandes en attente restent inchangés."}, +"pni_all.n_networks":{"one":"{n} réseau","other":"{n} réseaux"}, +"pni_all.n_of_total_connections":"{n} / {total} connexions", +"pni_all.n_of_total_pops":"{n} / {total} POP en commun", +"pni_all.n_orders_with_net":{"one":"{n} commande de PNI passée avec {net}. Inchangés : {kept} ; indisponibles : {blocked}.","other":"{n} commandes de PNI passées avec {net}. Inchangés : {kept} ; indisponibles : {blocked}."}, +"pni_all.new_and_upgrades":"Nouveaux : {fresh} · Augmentations : {up}", +"pni_all.no_shared_locations":"Aucun POP en commun disponible.", +"pni_all.no_shared_pops":"Tu n'as aucun POP en commun avec ce réseau.", +"pni_all.order_missing_and_upgrade_smaller":"Commande les PNI manquants et augmente la capacité des plus petits dans les POP en commun. Les PNI plus grands et les commandes en attente restent inchangés. Les POP indisponibles sont ignorés.", +"pni_all.peer_all_networks":"Peering avec tous les réseaux sur tous les POP", +"pni_all.peer_at_port":"Peering sur tous les POP · {port}", +"pni_all.peer_on_all_pops":"Peering sur tous les POP", +"pni_all.pni_size":"Capacité du PNI", +"pni_all.setup_total":"Coût total d'installation", +"pni_all.traffic_charges_apply":"Des frais de trafic de {price} par Gbps s'appliquent également.", "pnis.a_new_region_is_coming_online":"Une nouvelle région arrive bientôt. Elle arrive bientôt depuis 2019.", "pnis.about_n_days_to_go_nothing":"Encore environ {n} jours. Rien à faire qu’attendre, ou relancer.", "pnis.augment_with_net_delivered_in_city":"Extension avec {net} livrée à {city}.
Désormais {port}.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 83a3693..6ad0307 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2581,6 +2581,26 @@ "peering_policy.tried_a_remote_peer_once_it":"Hanno provato un peer remoto, una volta. Ha flappato durante il lancio di un prodotto. Mai più.", "pitcairn.uk_grant_mo":"Contributo UK {mo}/mese", "pitcairn.uk_grant_mo_once_islanders":"Contributo UK {mo}/mese quando gli isolani saranno online", +"pni_all.additional_per_month":"Costo mensile aggiuntivo", +"pni_all.all_at_port":"Peering con tutte le reti · {port}", +"pni_all.delivery_and_traffic_charges":"I tempi di consegna variano secondo la rete. Si applicano anche costi di peering basati sul traffico, dove previsti.", +"pni_all.n_blocked_connections":{"one":"{n} connessione non disponibile","other":"{n} connessioni non disponibili"}, +"pni_all.n_blocked_pops":{"one":"{n} POP non disponibile","other":"{n} POP non disponibili"}, +"pni_all.n_existing_or_pending_unchanged":{"one":"{n} PNI esistente o ordine in attesa resta invariato.","other":"{n} PNI esistenti o ordini in attesa restano invariati."}, +"pni_all.n_networks":{"one":"{n} rete","other":"{n} reti"}, +"pni_all.n_of_total_connections":"{n} / {total} connessioni", +"pni_all.n_of_total_pops":"{n} / {total} POP in comune", +"pni_all.n_orders_with_net":{"one":"{n} ordine PNI effettuato con {net}. Invariati: {kept}; non disponibili: {blocked}.","other":"{n} ordini PNI effettuati con {net}. Invariati: {kept}; non disponibili: {blocked}."}, +"pni_all.new_and_upgrades":"Nuovi: {fresh} · Upgrade: {up}", +"pni_all.no_shared_locations":"Nessun POP in comune disponibile.", +"pni_all.no_shared_pops":"Non hai POP in comune con questa rete.", +"pni_all.order_missing_and_upgrade_smaller":"Ordina i PNI mancanti e potenzia quelli più piccoli nei POP in comune. I PNI più grandi e gli ordini in attesa restano invariati. I POP non disponibili vengono saltati.", +"pni_all.peer_all_networks":"Peering con tutte le reti su tutti i POP", +"pni_all.peer_at_port":"Peering su tutti i POP · {port}", +"pni_all.peer_on_all_pops":"Peering su tutti i POP", +"pni_all.pni_size":"Capacità PNI", +"pni_all.setup_total":"Costo totale di attivazione", +"pni_all.traffic_charges_apply":"Si applicano anche costi di traffico di {price} per Gbps.", "pnis.a_new_region_is_coming_online":"Una nuova region arriverà presto. Arriva presto dal 2019.", "pnis.about_n_days_to_go_nothing":"Mancano circa {n} giorni. Non resta che aspettare, o sollecitare.", "pnis.augment_with_net_delivered_in_city":"Ampliamento con {net} consegnato a {city}.
Ora {port}.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index cd40592..e3fd3ba 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2581,6 +2581,26 @@ "peering_policy.tried_a_remote_peer_once_it":"Tentaram um peer remoto uma vez. Ele flapou durante um lançamento de produto. Nunca mais.", "pitcairn.uk_grant_mo":"Subsídio do Reino Unido {mo}/mês", "pitcairn.uk_grant_mo_once_islanders":"Subsídio do Reino Unido {mo}/mês quando os ilhéus estiverem online", +"pni_all.additional_per_month":"Custo mensal adicional", +"pni_all.all_at_port":"Peering com todas as redes · {port}", +"pni_all.delivery_and_traffic_charges":"Os prazos de entrega variam conforme a rede. Também se aplicam custos de peering baseados no tráfego, quando exigidos.", +"pni_all.n_blocked_connections":{"one":"{n} ligação indisponível","other":"{n} ligações indisponíveis"}, +"pni_all.n_blocked_pops":{"one":"{n} POP indisponível","other":"{n} POPs indisponíveis"}, +"pni_all.n_existing_or_pending_unchanged":{"one":"{n} PNI existente ou pedido pendente permanece inalterado.","other":"{n} PNIs existentes ou pedidos pendentes permanecem inalterados."}, +"pni_all.n_networks":{"one":"{n} rede","other":"{n} redes"}, +"pni_all.n_of_total_connections":"{n} / {total} ligações", +"pni_all.n_of_total_pops":"{n} / {total} POPs em comum", +"pni_all.n_orders_with_net":{"one":"{n} pedido de PNI feito com {net}. Inalterados: {kept}; indisponíveis: {blocked}.","other":"{n} pedidos de PNI feitos com {net}. Inalterados: {kept}; indisponíveis: {blocked}."}, +"pni_all.new_and_upgrades":"Novos: {fresh} · Upgrades: {up}", +"pni_all.no_shared_locations":"Não há POPs em comum disponíveis.", +"pni_all.no_shared_pops":"Não tens POPs em comum com esta rede.", +"pni_all.order_missing_and_upgrade_smaller":"Pede os PNIs em falta e aumenta os mais pequenos nos POPs em comum. Os PNIs maiores e os pedidos pendentes ficam inalterados. Os POPs indisponíveis são ignorados.", +"pni_all.peer_all_networks":"Peering com todas as redes em todos os POPs", +"pni_all.peer_at_port":"Peering em todos os POPs · {port}", +"pni_all.peer_on_all_pops":"Peering em todos os POPs", +"pni_all.pni_size":"Capacidade do PNI", +"pni_all.setup_total":"Custo total de instalação", +"pni_all.traffic_charges_apply":"Também se aplicam custos de tráfego de {price} por Gbps.", "pnis.a_new_region_is_coming_online":"Uma nova região vai entrar no ar em breve. Ela está entrando no ar em breve desde 2019.", "pnis.about_n_days_to_go_nothing":"Faltam cerca de {n} dias. Não há nada a fazer além de esperar, ou cobrar.", "pnis.augment_with_net_delivered_in_city":"Ampliação com {net} entregue em {city}.
Agora {port}.", diff --git a/src/game/70-rules/35-pni-orders.js b/src/game/70-rules/35-pni-orders.js new file mode 100644 index 0000000..c364a8e --- /dev/null +++ b/src/game/70-rules/35-pni-orders.js @@ -0,0 +1,23 @@ +/* Single and bulk orders share the same checks, prices and provisioning. */ +function pniQuote(city,net,tier,reserved=0){tier=+tier;const g1=tier===-1;if(g1)tier=0; + if(!S||!S.pops[city]||!isNet(net)||!NET[net].pops.includes(city)||!Number.isInteger(tier)||!PORT[tier]||(g1&&!pniG1(net)))return null; + const ex=S.pni.find(p=>p.city===city&&p.net===net); + if(ex&&(g1||!pniOn(ex)||ex.up||(!(ex.g1&&tier===0)&&tier<=ex.tier)))return null; + const cost=g1?PNI_G1_COST:(1500+PORT[tier].setup/2)*(ex&&ex.n||1),slots=ex?(PORT_SLOT(tier)-PORT_SLOT(ex.tier))*(ex.n||1):PORT_SLOT(tier); + let why='';if(!portOk(city,tier))why=tr('actions.your_router_can_t_take_a',{port:PORT[tier].n}); + else{const r=peerOk(net,'pni',city);if(!r.ok)why=tr('sites_peering_caches.net_declined_the_pni_why',{net:esc(NET[net].name),why:esc(r.why)}); + else if(!g1&&tier0&&portsUsed(city)+reserved+slots>portsMax(city)+1e-9)why=tr('ports.no_free_router_ports_in_city',{city:esc(CITY[city].name),u:fmtPorts(portsUsed(city)+reserved),m:portsMax(city)});} + return {city,net,tier,g1,ex,cost,slots,why};} +function pniPlace(q){const {city,net,tier,g1,ex}=q,lead=pniLead(net); + if(S.conf&&S.conf.until>S.day)S.stats.beerPni=1; + if(ex)ex.up={tier,n:ex.n||1,ready:S.day+lead,g1:false};else S.pni.push({id:uid(),city,net,tier,g1:g1||undefined,ready:S.day+lead}); + return lead;} +function pniBatch(net,tier){tier=+tier;const all=net===null;if(!S||(!all&&!isNet(net))||!Number.isInteger(tier)||(tier===-1?all||!pniG1(net):!PORT[tier]||!portShown(tier)))return null; + const shared=[],orders=[],blocked=[],reserved={};let kept=0,cost=0,mo=0; + // Pending augments and earlier orders in this batch already own their future ports. + for(const p of S.pni)if(p.up)reserved[p.city]=(reserved[p.city]||0)+Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1)); + for(const n of all?NETS:[NET[net]])for(const city of n.pops){if(!S.pops[city])continue;shared.push(city); + const q=pniQuote(city,n.id,tier,reserved[city]||0);if(!q){kept++;continue;}if(q.why){blocked.push(q);continue;}orders.push(q);cost+=q.cost;reserved[city]=(reserved[city]||0)+q.slots; + mo+=pniMo({net:n.id,tier:q.tier,g1:q.g1,n:q.ex&&q.ex.n},0)-(q.ex?pniMo(q.ex,0):0);} + return {shared,orders,blocked,kept,cost,mo};} diff --git a/src/game/90-actions/40-sites-peering-caches.js b/src/game/90-actions/40-sites-peering-caches.js index 05783be..cf4da86 100644 --- a/src/game/90-actions/40-sites-peering-caches.js +++ b/src/game/90-actions/40-sites-peering-caches.js @@ -12,13 +12,13 @@ Object.assign(ACT,{ unpeer:({city,net})=>{delete S.peers[net+'@'+city];after();}, peerAll:({city})=>{if(!isIx(city)||S.ixp[city]===undefined)return;const set=ixSessions(city);let n=0;for(const id of ixMembers(city))if(!set.has(id)&&peerOk(id,'ix',city).ok){S.peers[id+'@'+city]=true;n++;}if(!n)return;toast(trn('sites_peering_caches.n_new_session_at_ix_small',n,{ix:esc(ixName(city))}),'good',[],{a:'city',v:ixCity(city)});sfx('build');after();}, tailTog:()=>{UI.tailOpen=!UI.tailOpen;renderLeft();}, - pni:({city,net,tier})=>{tier=+tier;const g1=tier===-1;if(g1){if(!pniG1(net))return;tier=0;}if(!S.pops[city]||!NET[net]||!NET[net].pops.includes(city)||!PORT[tier])return;if(!portOk(city,tier)){toast(tr('actions.your_router_can_t_take_a',{port:PORT[tier].n}),'bad');sfx('err');return;}const r=peerOk(net,'pni',city);if(!r.ok){toast(tr('sites_peering_caches.net_declined_the_pni_why',{net:esc(NET[net].name),why:esc(r.why)}),'bad');sfx('err');after();return;} - if(!g1&&tierp.city===city&&p.net===net);if(ex&&(g1||!pniOn(ex)||ex.up))return;if(ex&&!(ex.g1&&tier===0)&&tier<=ex.tier)return; - const cost=g1?PNI_G1_COST:(1500+PORT[tier].setup/2)*(ex&&ex.n||1);if(!portGate(city,ex?(PORT_SLOT(tier)-PORT_SLOT(ex.tier))*(ex.n||1):PORT_SLOT(tier)))return;if(!spend(cost))return;if(S.conf&&S.conf.until>S.day)S.stats.beerPni=1; - // Nothing is instant: a cross-connect takes weeks, and the big networks quote months for a new PNI or an augment. - const lead=pniLead(net);if(ex)ex.up={tier,n:ex.n||1,ready:S.day+lead,g1:false};else S.pni.push({id:uid(),city,net,tier,g1:g1||undefined,ready:S.day+lead}); + pni:({city,net,tier})=>{const q=pniQuote(city,net,tier);if(!q)return;if(q.why){toast(q.why,'bad');sfx('err');after();return;}if(!spend(q.cost))return;const lead=pniPlace(q); toast(tr('sites_peering_caches.pni_with_net_ordered_eta_a',{net:esc(NET[net].name),eta:pniWhen(lead),dc:esc(siteName(city,'a'))}),'good');after();}, + pniAllOpen:({net})=>{pniAllModal(net);}, + pniAllSize:({v})=>{if(!UI.pniAll)return;pniAllModal(UI.pniAll.net,+v);$('modalCard').querySelector('[data-chg="pniAllSize"]')?.focus();}, + pniAll:({net,tier})=>{const b=pniBatch(net,tier);if(!b||!b.orders.length)return;if(!spend(b.cost))return; + for(const q of b.orders)pniPlace(q);UI.pniAll=null;closeModal(); + toast(trn('pni_all.n_orders_with_net',b.orders.length,{net:esc(net===null?tr('common.all_networks'):NET[net].name),kept:b.kept,blocked:b.blocked.length}),'good');after();}, pniChase:({id})=>{const p=S.pni.find(x=>x.id===id);if(!p||(pniOn(p)&&!p.up))return;const r=Math.random(); if(r<0.15){if(p.up)p.up.ready=Math.max(S.day+1,p.up.ready-30);else p.ready=Math.max(S.day+1,p.ready-30);toast(tr('sites_peering_caches.your_account_manager_found_the_order'),'good');} else toast(pick([tr('sites_peering_caches.it_is_with_the_provisioning_team'),tr('sites_peering_caches.we_are_waiting_on_the_colo'),tr('sites_peering_caches.your_ticket_was_merged_into_another'),tr('sites_peering_caches.could_you_resend_the_loa_you'),tr('sites_peering_caches.your_account_manager_is_on_paternity')]));after();}, diff --git a/src/game/94-dashboard/60-dashboard.js b/src/game/94-dashboard/60-dashboard.js index 5bb0282..85e9c64 100644 --- a/src/game/94-dashboard/60-dashboard.js +++ b/src/game/94-dashboard/60-dashboard.js @@ -18,8 +18,9 @@ function renderDash(){checkLayer(); {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 (AB?1:0)*dir||b.t-a.t;});} if(DT==='cust')h+=custSection(); if(DT==='conn')h+=connSection(); + if(DT==='traffic')h+=`
${btn(tr('pni_all.peer_all_networks'),'pniAllOpen',{net:null},'pink sm')}
`; if(DT==='traffic')h+=`

${tr('dashboard.traffic_by_network_asn')}

${tr('dashboard.where_your_users_traffic_comes_from')}

${['c','p','ix','t'].map(k=>`${EGC[k][0]}`).join('')}
${[['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])=>``).join('')} - ${nets.map(({n,e,t,want})=>{return ``;}).join('')}
${k==='mix'?l:``}
${logo(n)}${esc(n.name)}${n.asn}${TYPE_L[n.type]}${fmtG(t)}
${['c','p','ix','t'].map(k=>``).join('')}
${e.t>0.01?tr('common.price_mo',{price:fmt$((R.cost.transit||0)*e.t/tT)}):'—'}${want>0.01?pct(Math.max(0,1-t/want)):'—'}
`; + ${nets.map(({n,e,t,want})=>{return `${logo(n)}${esc(n.name)}${n.pops&&n.pops.some(c=>S.pops[c])?`
${btn(tr('pni_all.peer_on_all_pops'),'pniAllOpen',{net:n.id},'ghost sm')}
`:''}${n.asn}${TYPE_L[n.type]}${fmtG(t)}
${['c','p','ix','t'].map(k=>``).join('')}
${e.t>0.01?tr('common.price_mo',{price:fmt$((R.cost.transit||0)*e.t/tT)}):'—'}${want>0.01?pct(Math.max(0,1-t/want)):'—'}`;}).join('')}`; if(DT==='traffic'){const top=transitTop(S.transit.map(t=>t.id),8);if(top.length)h+=`

${tr('dashboard.who_your_transit_carries')}

${tr('dashboard.the_networks_you_pay_transit_to')}

${top.map(([id,v])=>`
${logo(NET[id])}
${esc(NET[id].name)} AS${NET[id].asn} · ${fmtG(v)} · ${tr('dashboard.about_price_mo',{price:fmt$((R.cost.transit||0)*v/tT)})}
${esc(offTransitHint(id))}
${btn(tr('common.where_6276'),'netFocus',{id},'ghost sm')}
`).join('')}
`;} 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); diff --git a/src/game/95-modals/35-pni-all.js b/src/game/95-modals/35-pni-all.js new file mode 100644 index 0000000..69f228e --- /dev/null +++ b/src/game/95-modals/35-pni-all.js @@ -0,0 +1,19 @@ +function pniAllModal(net,tier=1){const b=pniBatch(net,tier);if(!b)return;UI.pniAll={net,tier}; + const all=net===null,n=NET[net],port=tier===-1?'1G':PORT[tier].n,up=b.orders.filter(q=>q.ex).length,byNet={}; + if(all)for(const q of b.orders)(byNet[q.net]||(byNet[q.net]=[])).push(q.city); + const controls=`
${btn(all?tr('pni_all.all_at_port',{port}):tr('pni_all.peer_at_port',{port}),'pniAll',{net,tier},'pink',!b.orders.length||S.cash`; + const blocked=b.blocked.map(q=>`

${all?esc(NET[q.net].name)+' · ':''}${esc(CITY[q.city].name)}: ${q.why}

`).join(''); + openModal(`
${all?tr('common.all_networks'):`AS${n.asn} · ${esc(n.name)}`}

${all?tr('pni_all.peer_all_networks'):tr('pni_all.peer_on_all_pops')}

+

${tr('pni_all.order_missing_and_upgrade_smaller')}

+
+
${tr('pni_all.new_and_upgrades',{fresh:b.orders.length-up,up})}${all?tr('pni_all.n_of_total_connections',{n:b.orders.length,total:b.shared.length}):tr('pni_all.n_of_total_pops',{n:b.orders.length,total:b.shared.length})}
+
${tr('pni_all.setup_total')}${fmt$(b.cost)}
+
${tr('pni_all.additional_per_month')}${tr('common.price_mo',{price:fmt$(b.mo)})}
+ ${all?`

${tr('pni_all.delivery_and_traffic_charges')}

`:n.perG?`

${tr('pni_all.traffic_charges_apply',{price:fmt$(n.perG)})}

`:''} + ${S.cash${tr('interface.not_enough_cash_wait_for_revenue')}

`:''} + ${all?controls:''} + ${all&&b.orders.length?`
${trn('pni_all.n_networks',Object.keys(byNet).length)}${Object.entries(byNet).map(([id,cities])=>`
${esc(NET[id].name)}${trn('save.n_pop',cities.length)}

${cities.map(c=>esc(CITY[c].name)).join(' · ')}

`).join('')}
`:b.orders.length?`

${b.orders.map(q=>esc(CITY[q.city].name)).join(' · ')}

${pniEta(net)}

`:''} + ${b.kept?`

${trn('pni_all.n_existing_or_pending_unchanged',b.kept)}

`:''} + ${b.blocked.length?(all?`
${trn('pni_all.n_blocked_connections',b.blocked.length)}${blocked}
`:`

${trn('pni_all.n_blocked_pops',b.blocked.length)}

${blocked}`):''} + ${!b.shared.length?`

${all?tr('pni_all.no_shared_locations'):tr('pni_all.no_shared_pops')}

`:''} + ${all?'':controls}`);} diff --git a/src/i18n/en.js b/src/i18n/en.js index b26cc57..64c4e7f 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2582,6 +2582,26 @@ "peering_policy.tried_a_remote_peer_once_it":"Tried a remote peer once. It flapped during a product launch. Never again.", "pitcairn.uk_grant_mo":"UK grant {mo}/mo", "pitcairn.uk_grant_mo_once_islanders":"UK grant {mo}/mo once the islanders are online", +"pni_all.additional_per_month":"Additional monthly cost", +"pni_all.all_at_port":"Peer all networks · {port}", +"pni_all.delivery_and_traffic_charges":"Delivery times vary by network. Traffic-based peering charges also apply where required.", +"pni_all.n_blocked_connections":{"one":"{n} blocked connection","other":"{n} blocked connections"}, +"pni_all.n_blocked_pops":{"one":"{n} blocked POP","other":"{n} blocked POPs"}, +"pni_all.n_existing_or_pending_unchanged":{"one":"{n} existing PNI or pending order stays unchanged.","other":"{n} existing PNIs or pending orders stay unchanged."}, +"pni_all.n_networks":{"one":"{n} network","other":"{n} networks"}, +"pni_all.n_of_total_connections":"{n} / {total} connections", +"pni_all.n_of_total_pops":"{n} / {total} shared POPs", +"pni_all.n_orders_with_net":{"one":"{n} PNI order placed with {net}. Unchanged: {kept}; blocked: {blocked}.","other":"{n} PNI orders placed with {net}. Unchanged: {kept}; blocked: {blocked}."}, +"pni_all.new_and_upgrades":"New: {fresh} · Upgrades: {up}", +"pni_all.no_shared_locations":"No shared POPs are available.", +"pni_all.no_shared_pops":"You have no POPs in common with this network.", +"pni_all.order_missing_and_upgrade_smaller":"Orders missing PNIs and upgrades smaller ones at your shared POPs. Larger PNIs and pending orders stay unchanged. Unavailable POPs are skipped.", +"pni_all.peer_all_networks":"Peer all networks on all POPs", +"pni_all.peer_at_port":"Peer on all POPs · {port}", +"pni_all.peer_on_all_pops":"Peer on all POPs", +"pni_all.pni_size":"PNI size", +"pni_all.setup_total":"Total setup cost", +"pni_all.traffic_charges_apply":"Traffic charges of {price} per Gbps also apply.", "pnis.a_new_region_is_coming_online":"A new region is coming online soon. It has been coming online soon since 2019.", "pnis.about_n_days_to_go_nothing":"About {n} days to go. Nothing to do but wait, or chase it.", "pnis.augment_with_net_delivered_in_city":"Augment with {net} delivered in {city}.
Now {port}.", diff --git a/tests/pni-all.test.js b/tests/pni-all.test.js new file mode 100644 index 0000000..c6ba3b0 --- /dev/null +++ b/tests/pni-all.test.js @@ -0,0 +1,155 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +function setup(ev, cities = []) { + ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0"); + for (const city of cities) ev(`ACT.buildPop({city:'${city}'})`); + ev('for(const p of Object.values(S.pops))p.rgen=RG.length-1;compute()'); +} + +test('bulk PNIs add missing shared POPs and upgrade smaller ports once, preserving existing orders and LAGs', () => { + const { dom, ev, errors } = load(); + setup(ev, ['ams', 'lon', 'par', 'nyc', 'sjc', 'sao']); + ev(`S.pni.push( + {id:'small',net:'drz',city:'fra',tier:0,n:2,site:'ab',pref:'high'}, + {id:'big',net:'drz',city:'ams',tier:2}, + {id:'equal',net:'drz',city:'lon',tier:1}, + {id:'pending',net:'drz',city:'par',tier:0,ready:S.day+20}, + {id:'augment',net:'drz',city:'nyc',tier:0,up:{tier:1,n:1,ready:S.day+20}});compute()`); + const before = ev('JSON.stringify(S)'); + assert.deepEqual(JSON.parse(ev("JSON.stringify((b=>({shared:b.shared.length,orders:b.orders.length,kept:b.kept,cost:b.cost,mo:b.mo}))(pniBatch('drz',1)))")), + { shared: 6, orders: 2, kept: 4, cost: 6750, mo: 650 }); + assert.equal(ev('JSON.stringify(S)'), before, 'preview does not change the save'); + const cash = ev('S.cash'); + const existing = JSON.parse(ev("JSON.stringify(S.pni.filter(p=>p.id!=='small'))")); + ev("const originalAfter=after;window.after=()=>{window.afterCount=(window.afterCount||0)+1;originalAfter()};ACT.pniAll({net:'drz',tier:1})"); + assert.equal(ev('window.afterCount'), 1, 'one recompute/render/save for the whole batch'); + assert.equal(ev('S.cash'), cash - 6750); + assert.equal(ev('S.pni.length'), 6); + assert.equal(ev("S.pni.filter(p=>p.city==='sao'||p.city==='tok').length"), 0, 'only shared owned POPs'); + assert.deepEqual(JSON.parse(ev("JSON.stringify(S.pni.filter(p=>['big','equal','pending','augment'].includes(p.id)))")), existing); + assert.equal(ev("S.pni.find(p=>p.id==='small').up.n"), 2); + assert.equal(ev("S.pni.find(p=>p.id==='small').site"), 'ab'); + assert.equal(ev("S.pni.find(p=>p.id==='small').pref"), 'high'); + assert.ok(ev("S.pni.find(p=>p.city==='sjc').ready>S.day"), 'new PNIs still take time'); + ev("ACT.pniAll({net:'drz',tier:1})"); + assert.equal(ev('S.cash'), cash - 6750, 'repeat clicks neither charge nor duplicate'); + assert.equal(ev('window.afterCount'), 1); + ev('S=migrate(JSON.parse(JSON.stringify(packSave(S))));S.day=Math.max(...S.pni.map(p=>p.up?p.up.ready:p.ready||0));pniDay(S.day);compute()'); + assert.equal(ev("S.pni.find(p=>p.id==='small').tier"), 1, 'augment survives save migration and delivers'); + assert.equal(ev("S.pni.find(p=>p.city==='sjc').tier"), 1); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('bulk PNIs skip router speed, port capacity and policy restrictions with city-specific reasons', () => { + const { dom, ev, errors } = load(); + setup(ev, ['ams', 'lon', 'ash']); + ev(`S.pops.fra.rgen=0;S.pops.ams.rgen=1; + S.caches=Array.from({length:portsMax('ams')},()=>({id:uid(),city:'ams',net:'cfl'})); + while(['ams','lon'].some(c=>snub('msf',c)?.all))S.asn++; + compute();R.demTo.msf=1e4;ACT.pniAllOpen({net:'msf'});ACT.pniAllSize({v:'2'})`); + assert.equal(ev("pniBatch('msf',2).orders.length"), 1); + assert.equal(ev("pniBatch('msf',2).blocked.length"), 3); + const text = dom.window.document.getElementById('modalCard').textContent; + assert.match(text, /Frankfurt.*router can't take a 400G/s); + assert.match(text, /Amsterdam.*No free router ports/s); + assert.match(text, /Ashburn.*capacity|Ashburn.*sold out/s); + const cash = ev('S.cash'); + ev("ACT.pniAll({net:'msf',tier:2})"); + assert.equal(ev('S.pni.length'), 1); + assert.equal(ev('S.pni[0].city'), 'lon'); + assert.equal(ev('S.cash'), cash - 3500); + assert.match(ev("S.log[0].t"), /blocked: 3/); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('insufficient funds refuse the entire eligible batch and execution rechecks a stale preview', () => { + const { dom, ev, errors } = load(); + setup(ev, ['ams']); + ev("S.cash=pniBatch('drz',1).cost-1;ACT.pniAllOpen({net:'drz'})"); + assert.equal(dom.window.document.querySelector('#modalCard [data-act="pniAll"]').disabled, true); + const cash = ev('S.cash'); + ev("ACT.pniAll({net:'drz',tier:1})"); + assert.equal(ev('S.cash'), cash); + assert.equal(ev('S.pni.length'), 0); + ev("S.cash=1e8;ACT.pniAllOpen({net:'drz'});delete S.pops.ams;S.pops.fra.rgen=0;ACT.pniAll({net:'drz',tier:2})"); + assert.equal(ev('S.cash'), 1e8); + assert.equal(ev('S.pni.length'), 0, 'deleted POPs and unsupported speeds are rechecked on click'); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('bulk PNI actions reject invalid networks, sizes, minimum ports, traffic thresholds and non-shared locations', () => { + const { dom, ev, errors } = load(); + setup(ev); + ev('S.pops.fra.rgen=0'); + const cash = ev('S.cash'); + for (const net of ['missing', '__proto__', 'drz', 'nfx']) { + for (const tier of [-2, -1, 0.5, 99, NaN, Infinity]) ev(`ACT.pniAll({net:'${net}',tier:${tier}})`); + } + ev("ACT.pniAll({net:'nfx',tier:0});R.demTo.nfx=0;ACT.pniAll({net:'nfx',tier:1})"); + assert.equal(ev('S.pni.length'), 0); + assert.equal(ev('S.cash'), cash); + ev("delete S.pops.fra;ACT.pniAllOpen({net:'drz'});ACT.pniAll({net:'drz',tier:1})"); + assert.match(dom.window.document.getElementById('modalCard').textContent, /no POPs in common/); + assert.equal(dom.window.document.querySelector('#modalCard [data-act="pniAll"]').disabled, true); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('Doitsche 1G bulk orders and 10G augments keep paid-peering fees and conference delivery rules', () => { + const { dom, ev, errors } = load(); + setup(ev, ['ams']); + ev("S.conf={until:S.day+10,reg:'EU'};Math.random=()=>0.5"); + const cash = ev('S.cash'); + assert.equal(ev("pniBatch('dtk',-1).cost"), 2400); + assert.equal(ev("pniBatch('dtk',-1).mo"), ev('2*(PORT[0].pni/2+NET.dtk.paidFee)')); + ev("ACT.pniAll({net:'dtk',tier:-1})"); + assert.equal(ev('S.cash'), cash - 2400); + assert.equal(ev('S.stats.beerPni'), 1); + assert.equal(ev('S.pni.every(p=>p.g1&&pniG(p)===1&&p.ready===S.day+15)'), true); + ev('S.day+=15;pniDay(S.day);compute()'); + assert.equal(ev("pniBatch('dtk',0).mo"), 200, 'upgrades add port costs, without charging the peering fee twice'); + ev("ACT.pniAll({net:'dtk',tier:0});S.day=Math.max(...S.pni.map(p=>p.up.ready));pniDay(S.day)"); + assert.equal(ev('S.pni.every(p=>!p.g1&&pniG(p)===10)'), true); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('Traffic row buttons and size selection work by DOM events on phones in every language', () => { + for (const lang of ['en', 'it', 'pt', 'fr', 'es']) { + const { dom, ev, errors } = load(lang === 'en' ? {} : { lang }); + setup(ev); + dom.window.innerWidth = 360; + ev("ACT.launchBB({city:'fra'});ACT.dash();ACT.dashTab({k:'traffic'})"); + const doc = dom.window.document; + const buttons = [...doc.querySelectorAll('#dashCard [data-act="pniAllOpen"]')]; + assert.ok(buttons.length > 0, lang); + assert.equal(buttons.some(b => JSON.parse(b.dataset.args).net === '_tail'), false); + const cash = ev('S.cash'); + buttons.find(b => JSON.parse(b.dataset.args).net === 'cfl').click(); + assert.equal(doc.getElementById('modal').hidden, false, lang); + let select = doc.querySelector('#modalCard select'); + assert.equal(select.closest('label').textContent.includes(ev("tr('pni_all.pni_size')")), true, lang); + select.focus(); + select.value = '0'; + select.dispatchEvent(new dom.window.Event('change', { bubbles: true })); + select = doc.querySelector('#modalCard select'); + assert.equal(select.value, '0', lang); + assert.equal(doc.activeElement, select, 'size changes preserve keyboard focus'); + const submit = doc.querySelector('#modalCard [data-act="pniAll"]'); + assert.equal(JSON.parse(submit.dataset.args).tier, 0, lang); + assert.equal(submit.disabled, false, lang); + assert.equal(ev('S.cash'), cash, 'opening or changing the preview spends nothing'); + submit.click(); + assert.equal(doc.getElementById('modal').hidden, true, lang); + assert.equal(ev("S.pni.some(p=>p.net==='cfl'&&p.city==='fra'&&p.tier===0)"), true, lang); + assert.equal(ev('S.cash'), cash - 1750, lang); + assert.doesNotMatch(doc.getElementById('modalCard').textContent, /pni_all\./, lang); + assert.deepEqual(errors, [], lang); + dom.window.close(); + } +}); diff --git a/tests/pni-global.test.js b/tests/pni-global.test.js new file mode 100644 index 0000000..e175ed2 --- /dev/null +++ b/tests/pni-global.test.js @@ -0,0 +1,135 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +function setup(ev) { + ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.pops.fra.rgen=RG.length-1;compute()"); +} + +test('global PNIs cover every eligible network and shared POP, including the long tail, in one transaction', () => { + const { dom, ev, errors } = load(); + setup(ev); + ev(`ACT.buildPop({city:'ams'});S.pops.ams.rgen=RG.length-1; + S.pni.push({id:'small',net:'cfl',city:'fra',tier:0,n:2,site:'ab',pref:'high'}, + {id:'big',net:'drz',city:'ams',tier:2}, + {id:'pending',net:'nfx',city:'fra',tier:1,ready:S.day+30}); + compute();for(const n of NETS)R.demTo[n.id]=1e4`); + const before = ev('JSON.stringify(S)'); + const batch = JSON.parse(ev('JSON.stringify(pniBatch(null,1))')); + assert.equal(ev('JSON.stringify(S)'), before, 'global preview changes no game state'); + assert.ok(batch.orders.some(q => q.net === 'cfl' && q.city === 'fra' && q.ex)); + assert.ok(batch.orders.some(q => q.net === 'cfl' && q.city === 'ams' && !q.ex)); + assert.ok(batch.orders.some(q => ev(`NET['${q.net}'].tail`)), 'small networks are included'); + assert.equal(batch.orders.some(q => q.net === 'drz' && q.city === 'ams'), false, 'no downgrade'); + assert.equal(batch.orders.some(q => q.net === 'nfx' && q.city === 'fra'), false, 'keep pending orders'); + const cash = ev('S.cash'); + ev("const originalAfter=after;window.after=()=>{window.afterCount=(window.afterCount||0)+1;originalAfter()};ACT.pniAll({net:null,tier:1})"); + assert.equal(ev('window.afterCount'), 1); + assert.equal(ev('S.cash'), cash - batch.cost); + assert.equal(ev('S.pni.length'), 3 + batch.orders.filter(q => !q.ex).length); + assert.equal(ev('new Set(S.pni.map(p=>p.net+"@"+p.city)).size'), ev('S.pni.length')); + assert.equal(ev("S.pni.every(p=>S.pops[p.city]&&NET[p.net].pops.includes(p.city))"), true); + assert.equal(ev("S.pni.find(p=>p.id==='small').up.n"), 2, 'LAG members stay together'); + assert.equal(ev("S.pni.find(p=>p.id==='small').pref"), 'high'); + assert.equal(ev("S.pni.find(p=>p.id==='big').tier"), 2); + assert.equal(ev('Object.keys(S.pops).every(c=>portsUsed(c)<=portsMax(c))'), true); + ev('S=migrate(JSON.parse(JSON.stringify(packSave(S))));compute()'); + assert.equal(ev('S.pni.length'), 3 + batch.orders.filter(q => !q.ex).length); + assert.equal(ev("S.pni.find(p=>p.id==='small').up.tier"), 1); + const count = ev('S.pni.length'); + ev('ACT.pniAll({net:null,tier:1})'); + assert.equal(ev('S.cash'), cash - batch.cost, 'repeat clicks spend nothing'); + assert.equal(ev('S.pni.length'), count); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('global PNIs share the available router ports, including four 10G breakouts per slot', () => { + for (const [tier, count] of [[1, 1], [0, 4]]) { + const { dom, ev, errors } = load(); + setup(ev); + ev("S.pops.fra.rgen=0;S.caches=Array.from({length:7},()=>({id:uid(),city:'fra',net:'cfl'}));compute()"); + assert.equal(ev(`pniBatch(null,${tier}).orders.length`), count); + assert.ok(ev(`pniBatch(null,${tier}).blocked.some(q=>/No free router ports/.test(q.why))`)); + ev(`ACT.pniAll({net:null,tier:${tier}})`); + assert.equal(ev('S.pni.length'), count); + assert.equal(ev("portsUsed('fra')"), 8); + const cash = ev('S.cash'); + ev(`ACT.pniAll({net:null,tier:${tier}})`); + assert.equal(ev('S.cash'), cash); + assert.deepEqual(errors, []); + dom.window.close(); + } +}); + +test('global planning reserves ports for pending speed and LAG augments without mutating the save', () => { + for (const [tier, n] of [[1, 1], [0, 4]]) { + const { dom, ev, errors } = load(); + setup(ev); + ev(`S.pops.fra.rgen=0;S.caches=Array.from({length:7},()=>({id:uid(),city:'fra',net:'cfl'})); + S.pni=[{id:'pending',city:'fra',net:'cfl',tier:0,n:1,up:{tier:${tier},n:${n},ready:S.day+30}}];compute()`); + const state = ev('JSON.stringify(S)'); + assert.equal(ev('pniBatch(null,0).orders.length'), 0); + assert.equal(ev('pniBatch(null,1).orders.length'), 0); + assert.equal(ev('JSON.stringify(S)'), state); + const cash = ev('S.cash'); + ev('ACT.pniAll({net:null,tier:1})'); + assert.equal(ev('S.pni.length'), 1); + assert.equal(ev('S.cash'), cash); + assert.deepEqual(errors, []); + dom.window.close(); + } +}); + +test('global PNIs require the full budget and reject unsupported sizes and an empty POP list', () => { + const { dom, ev, errors } = load(); + setup(ev); + ev('S.cash=pniBatch(null,1).cost-1;ACT.pniAllOpen({net:null})'); + const cash = ev('S.cash'); + assert.equal(dom.window.document.querySelector('#modalCard [data-act="pniAll"]').disabled, true); + ev('ACT.pniAll({net:null,tier:1})'); + assert.equal(ev('S.cash'), cash); + assert.equal(ev('S.pni.length'), 0, 'no partial purchase'); + for (const tier of [-2, -1, 0.5, 99, NaN, Infinity]) ev(`ACT.pniAll({net:null,tier:${tier}})`); + ev('ACT.pniAll({tier:1});S.pops={};ACT.pniAllOpen({net:null})'); + assert.equal(ev('S.cash'), cash); + assert.equal(ev('S.pni.length'), 0); + assert.match(dom.window.document.getElementById('modalCard').textContent, /No shared POPs/); + assert.equal(dom.window.document.querySelector('#modalCard [data-act="pniAll"]').disabled, true); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('the global Traffic button preserves scope, keyboard focus and translations on phones', () => { + for (const lang of ['en', 'it', 'pt', 'fr', 'es']) { + const { dom, ev, errors } = load(lang === 'en' ? {} : { lang }); + setup(ev); + dom.window.innerWidth = 360; + ev("ACT.dash();ACT.dashTab({k:'traffic'})"); + const doc = dom.window.document; + const button = [...doc.querySelectorAll('#dashCard [data-act="pniAllOpen"]')].find(b => JSON.parse(b.dataset.args).net === null); + assert.ok(button, lang); + button.click(); + assert.equal(doc.querySelector('#modalCard h2').textContent, ev("tr('pni_all.peer_all_networks')"), lang); + const cash = ev('S.cash'); + const select = doc.querySelector('#modalCard select'); + assert.equal([...select.options].some(o => o.value === '-1'), false, '1G is not available for all networks'); + select.focus(); + select.value = '0'; + select.dispatchEvent(new dom.window.Event('change', { bubbles: true })); + assert.equal(doc.activeElement, doc.querySelector('#modalCard select')); + const submit = doc.querySelector('#modalCard [data-act="pniAll"]'); + assert.deepEqual(JSON.parse(submit.dataset.args), { net: null, tier: 0 }, lang); + assert.equal(submit.disabled, false, lang); + assert.ok(doc.querySelectorAll('#modalCard details').length > 0, 'long lists are collapsed'); + assert.equal(ev('S.cash'), cash, 'preview does not buy anything'); + assert.doesNotMatch(doc.getElementById('modalCard').textContent, /pni_all\./, lang); + const cost = ev('pniBatch(null,0).cost'); + submit.click(); + assert.equal(doc.getElementById('modal').hidden, true, lang); + assert.equal(ev('S.cash'), cash - cost, lang); + assert.ok(ev('new Set(S.pni.map(p=>p.net)).size') > 1, lang); + assert.deepEqual(errors, [], lang); + dom.window.close(); + } +});