${btn(tr('pie.found_price',{price:fmt$(piePrice(PIE_CO)),mo:fmt$(PIE_CO_MO)}),'pieFound',{},'pink',!can)}
`;openModal(h,'pie');return;}
const tab=(k,l)=>`${tab('traffic',tr('pie_traffic.tab'))}${tab('co',tr('pie.tab_company'))}${tab('fly',tr('pie.tab_launch'))}${tab('dish',tr('pie.tab_dishes'))}${tab('book',tr('pie.tab_founder'))}
`;
+ h+=`${tab('traffic',tr('pie_traffic.tab'))}${tab('co',tr('pie.tab_company'))}${tab('fly',tr('pie.tab_launch'))}${tab('dish',tr('pie.tab_dishes'))}${tab('gov',tr('pie_gov.tab'))}${tab('book',tr('pie.tab_founder'))}
`;
const cities=Object.keys(S.pops).sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name)),c=S.pops[UI.pieCity]?UI.pieCity:cities[0];
const sel=`${tr('common.cash')}
${fmt$(S.cash)}
${S.cash<0?tr('bank.bankrupt_at_100k'):tr('bank.in_the_vault')}
${tr('dashboard.monthly_p_l')}
${net>=0?'+':''}${fmt$(net)}
${tr('bank.after_loan_payments')}
diff --git a/src/i18n/en.js b/src/i18n/en.js
index 05ca6a9..c25dbdf 100644
--- a/src/i18n/en.js
+++ b/src/i18n/en.js
@@ -307,6 +307,10 @@
"banks.do_the_kehrwoche_keep_your_noc":"Do the Kehrwoche: keep your NOC free of incidents older than a week.",
"banks.download_our_app_and_enable_all":"Download our app and enable all notifications.",
"banks.every_pop_needs_a_backup_generator":"Every POP needs a backup generator. Our risk team saw one disaster movie.",
+"banks.exim_blurb":"The state lends you money to buy rockets from home. Space covenants apply.",
+"banks.exim_keep_a_dish_in":"Keep a pie dish in {a}",
+"banks.exim_launch_n_pies_by":"Launch {n} pies by {d} ({f} so far)",
+"banks.exim_launch_pies":"Launch the pies you promised",
"banks.fill_in_form_t_17b_in":"Fill in form T-17b in triplicate, every month, forever.",
"banks.give_our_ceo_s_nephew_a":"Give our CEO’s nephew a job. He needs {price}/mo and a parking spot.",
"banks.instant_approval_instant_regret":"Instant approval. Instant regret.",
@@ -3509,6 +3513,42 @@
"pie_globe.switch_to_day_view":"Switch to day view",
"pie_globe.switch_to_night_view":"Switch to night view",
"pie_globe.your_pies_in_orbit":"Your pies in orbit, drag to turn the Earth",
+"pie_gov.ask":"Ask {mo}/mo",
+"pie_gov.bid":"Bid",
+"pie_gov.closes":"bids close {d}",
+"pie_gov.cov_dish":"Keep a pie dish in {a}",
+"pie_gov.cov_launch":"Launch {n} pies by {d}",
+"pie_gov.due":"Needs {p} served by {d}",
+"pie_gov.exim":"Ex-Im Pie Bank",
+"pie_gov.exim_breach":"Break a covenant and the rate goes up {apr} points, the deadline moves and the lending country gets cross.",
+"pie_gov.exim_none":"No offer right now. The bank lends to rocket companies with a factory.",
+"pie_gov.exim_offer":"Lends you {amt} at {apr}% for {n} months: {pay}/mo.",
+"pie_gov.no_auction":"No auction open. The fund calls when a town only your pies reach is up for support.",
+"pie_gov.open":"Open",
+"pie_gov.pitcairn":"Pitcairn",
+"pie_gov.pitcairn_note":"The UK pays {mo}/mo while the islanders are well served, and accepts satellite service for {sky}/mo.",
+"pie_gov.rdf":"Rural Digital Pie Fund",
+"pie_gov.rdf_note":"Reverse auctions for towns only orbit reaches: the lowest ask wins and is paid monthly for {y} years. Keep the town {p} served, averaged over each month: two months under it in a row and the award is revoked and {c} of the last year's support is clawed back.",
+"pie_gov.rival_coop":"Co-op de Ville",
+"pie_gov.rival_hugsnet":"HugsNet",
+"pie_gov.rival_viasad":"ViaSad",
+"pie_gov.served":"{p} served",
+"pie_gov.t_auction":"Support for {city}: up to {mo}/mo for {y} years. Bids close {d}.",
+"pie_gov.t_auction_title":"Rural Digital Pie Fund auction",
+"pie_gov.t_bid":"Bid in for {city}: {mo}/mo. Results on {d}.",
+"pie_gov.t_breach":"The Ex-Im Pie Bank tightens your terms: {apr}% now, and {a} is not amused.",
+"pie_gov.t_breach_spat":"Its government has questions.",
+"pie_gov.t_done":"The fund's support for {city} has ended: {amt} paid in all.",
+"pie_gov.t_exim":"The Ex-Im Pie Bank would lend you {amt} at almost nothing, if you keep a pie dish in {a}.",
+"pie_gov.t_exim_title":"State money for rockets",
+"pie_gov.t_lost":"{rival} won {city} asking only {mo}/mo.",
+"pie_gov.t_revoked":"Award for {city} revoked: {p} served, the fund wants {need}. It claws back {amt}.",
+"pie_gov.t_warn":"The fund is watching {city}: {p} served last month, it wants {need}. Another month like that and the award is revoked.",
+"pie_gov.t_won":"You won {city}: {mo}/mo. Have it {p} served by {d}.",
+"pie_gov.tab":"Gov",
+"pie_gov.until":"Paid until {d}",
+"pie_gov.up_to":"up to {mo}/mo",
+"pie_gov.warned":"one more bad month and it is revoked",
"pie_inc.dig_msg":"A backhoe found the backhaul fiber under the pie dish in {city}. The dish is fine, but its traffic has nowhere to go.",
"pie_inc.dig_press":"The press office says: the dish is taking a well-earned break from the ground.",
"pie_inc.food_fix":"Buy a Space Roomba",
@@ -3661,6 +3701,7 @@
"pie_traffic.via_dishes":"up at {up}, down at {down}",
"pitcairn.uk_grant_mo":"UK grant {mo}/mo",
"pitcairn.uk_grant_mo_once_islanders":"UK grant {mo}/mo once the islanders are online",
+"pitcairn.uk_sky_grant_mo":"UK satellite grant {mo}/mo (fiber gets {full})",
"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.",
diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js
index 2d54560..91e9080 100644
--- a/tests/gameplay-rules.test.js
+++ b/tests/gameplay-rules.test.js
@@ -627,11 +627,12 @@ test('O5: launches fail only with chaos on, never in the first 90 days after the
test('O7: a fresh Tier 1 cannot afford a full Shortcrust in its first year', () => {
// Reference: the big-network benchmark save, a won network far larger than a fresh Tier 1. A year of its profit at
- // today's revenue (costs ignored, so generously) plus the largest loan any bank offers (12x monthly revenue).
+ // today's revenue (costs ignored, so generously) plus the largest loan any bank offers (12x monthly revenue), and the
+ // most the Ex-Im Pie Bank lends a rocket company on top.
const g = load();
const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
g.ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));compute()`);
- const rev = g.ev('R.revMo'), loan = g.ev('Math.max(...Object.values(BANKS).map(b=>b.amt[1]))') * rev, cash = Math.max(0, g.ev('S.cash'));
+ const rev = g.ev('R.revMo'), loan = g.ev('Math.max(...Object.values(BANKS).map(b=>b.amt[1]))') * rev + g.ev('pieEximCap()'), cash = Math.max(0, g.ev('S.cash'));
const year = 12 * rev + loan + Math.min(cash, 12 * rev);
const full = g.ev("pieFullCost('short')");
assert.ok(full > 5e9, `O7: a full Shortcrust costs ${Math.round(full / 1e6)}M`);
diff --git a/tests/pie-balance.test.js b/tests/pie-balance.test.js
index 417bfe3..3897434 100644
--- a/tests/pie-balance.test.js
+++ b/tests/pie-balance.test.js
@@ -3,7 +3,7 @@
// Seeded. Orbit is judged on its own books (S.pie.book): the fixture's ground network loses money on its own.
// It plays until the books balance (at most 10 years). PIE_BALANCE_YEARS=10 node --test tests/pie-balance.test.js plays
// that many years whatever happens and prints them year by year, PIE_BALANCE_DIAG=1 also monthly with the spending by kind
-// and PIE_BALANCE_SEED another seed (for tuning).
+// and PIE_BALANCE_SEED another seed (for tuning). PIE_BALANCE_GOV=1 plays only the run with government money (below).
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
@@ -21,9 +21,11 @@ const YEARS = +(process.env.PIE_BALANCE_YEARS || 0);
// there at least 97% up) hold less than 1.3x what is sold, a new dish when every healthy dish has 16, at a well-served
// POP under the crust (fiber at least 98% up), cheapest landing rights first, the first eight spread out;
// - landing rights renewed before they lapse, every orbit offer signed.
+// With gov (the second test), the same player also takes government money: asks 50% in every Rural Digital Pie Fund
+// auction, takes the Ex-Im Pie Bank's loan and keeps a dish in its country (the covenant).
// compute() runs every 30 days and whenever what the sky carries changes (coverage in 10% steps, hubs, lasers,
// safe mode, an orbit incident or spat starting or ending); orbit income is booked from the last one, as in the game.
-function sim(days, stop = false, seed = 7) {
+function sim(days, stop = false, seed = 7, gov = false) {
const g = load({ seed });
const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
g.ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));S.pieV=1;UI.started=true;UI.pitched=true;UI.speed=0;S.nextFail=1e9;S.nextEvent=1e9;
@@ -41,12 +43,17 @@ function sim(days, stop = false, seed = 7) {
if(d)ACT.pieAnt({id:d.id});else{const c=__site();if(c){if(!pieLicOk(CITY[c].cc))ACT.pieLic({cc:CITY[c].cc});ACT.pieDish({city:c});}}}}
for(const d of P.dishes){const l=P.lic[CITY[d.city].cc];if(l&&l.state==='ok'&&l.until-S.day<5)ACT.pieLic({cc:CITY[d.city].cc});}
for(const o of S.offers.filter(o=>BIZ_T[o.type].orbit))ACT.accept({id:o.id});
- const key=[pieHubs().join(),Math.round(pieCarry('short')*10),Math.round(pieCov('short')*10),pieLased('short'),P.safe,S.inc.filter(i=>PIE_INC.includes(i.type)&&i.until>S.day).map(i=>i.id).join(),Object.keys(P.spat).join()].join('|');if(key!==window.__key)dirty=true;window.__key=key;
+ if(window.__gov){const G=P.gov;for(const a of G.auc)if(a.bid!==0.5)ACT.pieBid({id:a.id,f:0.5});if(G.ex)ACT.pieExim();
+ const l=pieEximLoan();if(l&&!pieEximDishOk(l)){const c=Object.keys(S.pops).filter(c=>CITY[c].cc===l.pie.cc&&pieCovers('short',c)&&!P.dishes.some(x=>x.city===c)).sort((a,b)=>sfOf(R,b)-sfOf(R,a))[0];
+ if(c){if(!pieLicOk(l.pie.cc))ACT.pieLic({cc:l.pie.cc});ACT.pieDish({city:c});}}}
+ const key=[pieHubs().join(),Math.round(pieCarry('short')*10),Math.round(pieCov('short')*10),pieLased('short'),P.safe,S.inc.filter(i=>PIE_INC.includes(i.type)&&i.until>S.day).map(i=>i.id).join(),Object.keys(P.spat).join(),P.gov.aw.length].join('|');if(key!==window.__key)dirty=true;window.__key=key;
const real=compute;compute=()=>{if(dirty||S.day%30===0){window.__nC=(window.__nC||0)+1;real();}};try{dayTick();}finally{compute=real;}};
window.__year=()=>({y:Math.round(S.day/360),spent:S.pie.book.spent,earned:S.pie.book.earned,mo:(R.pie&&R.pie.rev)||0,cov:pieCov('short'),cust:S.biz.filter(b=>BIZ_T[b.type].orbit).length,dishes:S.pie.dishes.length,nC:window.__nC|0});
- closeModal()`);
+ window.__gov=${gov};closeModal()`);
if (process.env.PIE_BALANCE_DIAG) g.ev(`window.__B={};for(const k of ['pieLaunch','pieDish','pieAnt','pieLic','pieRd','pieFound','pieFactory','piePad','fixInc','pieSpatPick']){const f=ACT[k];if(!f)continue;ACT[k]=a=>{const s0=S.pie.book.spent;const r=f(a);__B[k]=(__B[k]||0)+(S.pie.book.spent-s0)/1e6;return r;};}
- {const f=pieDay;pieDay=d=>{const s0=S.pie.book.spent;f(d);__B.day=(__B.day||0)+(S.pie.book.spent-s0)/1e6;};}`);
+ {const f=pieDay;pieDay=d=>{const s0=S.pie.book.spent;f(d);__B.day=(__B.day||0)+(S.pie.book.spent-s0)/1e6;};}
+ {const f=pieRdfRevoke;pieRdfRevoke=(w,avg)=>{(window.__L=window.__L||[]).push(['revoked',S.day,w.city,S.pops[w.city]?'pop':'terminals',avg.toFixed(2),Math.round(w.mo/1e6)+'M/mo',S.biz.filter(b=>b.city===w.city&&BIZ_T[b.type].orbit).length].join(' '));f(w,avg);};}
+ {const f=pieRdfClose;pieRdfClose=a=>{if(a.bid&&a.bid<=a.riv)(window.__L=window.__L||[]).push(['award',S.day,a.city,S.pops[a.city]?'pop':'terminals',CITY[a.city].P,Math.round(a.ask*a.bid/1e6)+'M/mo'].join(' '));f(a);};}`);
const rows = [];
try {
const d0 = g.ev('S.day');
@@ -71,7 +78,8 @@ function payback(rows) {
return net > 0 ? b.y + (b.spent - b.earned) / net : Infinity;
}
-test('O7: a full lasered Shortcrust, run sensibly through the game loop, pays back in 5 to 10 years', { timeout: 600000 }, () => {
+let BASE = null;
+test('O7: a full lasered Shortcrust, run sensibly through the game loop, pays back in 5 to 10 years', { timeout: 600000, skip: !!process.env.PIE_BALANCE_GOV }, () => {
const years = YEARS || 10;
const { rows, errors } = sim(360 * years, !YEARS, +(process.env.PIE_BALANCE_SEED || 7));
if (YEARS) for (const r of rows) console.log(`year ${r.y}: spent ${(r.spent / 1e9).toFixed(2)}B, earned ${(r.earned / 1e9).toFixed(2)}B, orbit ${(r.mo / 1e6).toFixed(0)}M/mo, ${Math.round(r.cov * 100)}% covered, ${r.cust} customers, ${r.dishes} dishes, ${r.nC} computes`);
@@ -80,6 +88,25 @@ test('O7: a full lasered Shortcrust, run sensibly through the game loop, pays ba
assert.ok(last.cov > 0.9, `O7: the crust is full after ${years} years (${Math.round(last.cov * 100)}%)`);
assert.ok(last.cust > 30, `O7: customers stay (${last.cust})`);
assert.ok(y >= 5, `O7: a full Shortcrust pays back in ${y.toFixed(1)} years; make orbit dearer or its customers fewer`);
+ BASE = y;
assert.ok(y <= 10, `O7: a full Shortcrust pays back in ${y.toFixed(1)} years (spent ${(last.spent / 1e9).toFixed(1)}B, earned ${(last.earned / 1e9).toFixed(1)}B by year ${last.y}); make orbit cheaper or its customers more`);
assert.deepEqual(errors, []);
});
+
+// Government money (src/game/60-features/99-pie-subsidies.js, the Pitcairn grant has no town in this save) helps, but
+// never turns the constellation into a bargain: at most two years sooner than without it, and never under four.
+test('O7: government money pays back sooner, by two years at most', { timeout: 600000 }, () => {
+ const years = YEARS || 10, seed = +(process.env.PIE_BALANCE_SEED || 7);
+ const { rows, errors, ev } = sim(360 * years, !YEARS, seed, true);
+ if (YEARS) for (const r of rows) console.log(`gov year ${r.y}: spent ${(r.spent / 1e9).toFixed(2)}B, earned ${(r.earned / 1e9).toFixed(2)}B, orbit ${(r.mo / 1e6).toFixed(0)}M/mo, ${r.cust} customers`);
+ const y = payback(rows), st = JSON.parse(ev('JSON.stringify({won:S.stats.pieRdf|0,lost:S.stats.pieRdfLost|0,aw:S.pie.gov.aw.length,mo:pieGovMo(),exim:(S.loans.find(l=>l.bank===\'exim\')||{}).pie||null})'));
+ if (process.env.PIE_BALANCE_DIAG) for (const l of JSON.parse(ev('JSON.stringify(window.__L||[])'))) console.log(l);
+ if (YEARS) console.log(`gov payback: year ${y.toFixed(1)} (${st.won} awards won, ${st.lost} revoked, ${st.aw} in force at ${(st.mo / 1e6).toFixed(1)}M/mo, Ex-Im ${JSON.stringify(st.exim)})`);
+ assert.ok(st.won > 0, 'the fund awarded something');
+ assert.ok(y >= 4, `O7: with government money a full Shortcrust pays back in ${y.toFixed(1)} years; the fund pays too much`);
+ if (BASE !== null) {
+ assert.ok(y <= BASE + 0.3, `government money must not slow payback (the runs differ by chance after the first auction) (${y.toFixed(1)} vs ${BASE.toFixed(1)})`);
+ assert.ok(BASE - y <= 2, `O7: government money pays back ${(BASE - y).toFixed(1)} years sooner (${y.toFixed(1)} vs ${BASE.toFixed(1)}); the fund pays too much`);
+ }
+ assert.deepEqual(errors, []);
+});
diff --git a/tests/pie-gov.test.js b/tests/pie-gov.test.js
new file mode 100644
index 0000000..d56ec80
--- /dev/null
+++ b/tests/pie-gov.test.js
@@ -0,0 +1,263 @@
+// Pie in the Sky: government money (src/game/60-features/99-pie-subsidies.js, 85-pitcairn.js). The Rural Digital Pie
+// Fund's auctions and awards, the Ex-Im Pie Bank's loan and its space covenants, and Pitcairn's satellite grant.
+// Seeded; auctions, rival bids and days are set or driven directly, so nothing depends on luck.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { load } = require('./harness');
+
+// The backhaul world (tests/pie-backhaul.test.js): a London – New York – Auckland backbone, a full lasered Shortcrust and
+// Pitcairn on its own, with broadband and a dish, reaching the backbone only through orbit.
+const pitcairn = (ev) => {
+ ev("ACT.modeSet({m:'sandbox'});ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.nextFail=1e9;S.nextEvent=1e9");
+ ev("for(const c of ['lon','nyc','akl','pcn'])if(!S.pops[c])ACT.buildPop({city:c});S.links=[];"
+ + "S.links.push({id:'ln',a:'lon',b:'nyc',kind:'wave',tier:3,km:5818,sub:true,cable:'grace',cut:0,mo:1},{id:'na',a:'nyc',b:'akl',kind:'wave',tier:3,km:14200,sub:true,cut:0,mo:1});for(const c of ['lon','nyc'])ACT.buyTransit({city:c,net:'cog',tier:1});ACT.buyTransit({city:'akl',net:'sgt',tier:1})");
+ ev("ACT.pieFound();for(const c of ['lon','nyc','akl','pcn']){ACT.pieDish({city:c});S.pie.lic[CITY[c].cc]={state:'ok',until:1e6};}for(const x of S.pie.dishes)x.ant=PIE_ANT_MAX");
+ ev("S.pops.pcn.bb={d:5};S.pie.crusts.short.cohorts=[{n:CRUSTS.short.full,day:S.day,las:true}];compute()");
+};
+// The spats world (tests/pie-spats.test.js): a normal game with real chaos and open gates, dishes in NL, BE, DE, SG.
+const sky = (ev) => {
+ ev("beginGame('Sky','fra',{mode:'normal',preset:'oncall',rules:{gates:'open'}});if(UI.pendGame)ACT.pitchSkip();S.cash=1e12;S.nextFail=1e9;S.nextEvent=1e9;S.monkey&&(S.monkey.next=1e9)");
+ ev("for(const c of ['sin','ams','bru','lon'])ACT.buildPop({city:c});ACT.pieFound();ACT.pieFactory();ACT.piePad({city:'sin'});for(const c of ['ams','bru','fra','sin'])ACT.pieDish({city:c});for(const cc of ['NL','BE','DE','SG'])ACT.pieLic({cc})");
+ ev('pieCohort(\'short\',1200,true);S.day=S.pie.born+120;compute();S.pie.stock=400');
+};
+const J = (ev, x) => JSON.parse(ev(`JSON.stringify(${x})`));
+// Days of the fund alone (no failures, no other randomness): the day counter and pieGovDay().
+const govDays = (ev, n) => ev(`for(let i=0;i<${n};i++){S.day++;pieGovDay(S.day);}`);
+
+test('Pitcairn served from orbit earns the UK satellite grant: less than the fiber grant, latency forgiven', () => {
+ const { ev, errors } = load();
+ pitcairn(ev);
+ assert.ok(ev("sfOf(R,'pcn')") < 0.9, `orbit's latency keeps sfOf under the fiber bar (${ev("sfOf(R,'pcn')")})`);
+ assert.equal(ev('grantOn(R)'), false, 'no fiber grant');
+ assert.equal(ev('grantSky(R)'), true, 'but the satellite tier');
+ assert.equal(ev('R.rev.grant'), ev('GRANT_SKY_MO'));
+ assert.ok(ev('GRANT_SKY_MO') < ev('GRANT_MO'), 'it pays less');
+ assert.equal(ev('R.pie.gov.sky'), ev('GRANT_SKY_MO'), 'and counts in the orbit\'s books');
+ ev('S.pie.book.earned=0;R.pie.gov.rdf=0;pieGovDay(S.day)');
+ assert.ok(Math.abs(ev('S.pie.book.earned') - ev('GRANT_SKY_MO') / 30) < 1e-6, 'a day of it is booked');
+ assert.match(ev("grantFact('pcn')"), /satellite grant/);
+ // Under the bar (a dish of one antenna for a big town) or no orbit at all: nothing.
+ ev("S.pops.pcn.bb={d:300};S.pie.dishes.find(x=>x.city==='pcn').ant=1;compute()");
+ assert.equal(ev('R.rev.grant'), 0, 'a full pipe is not service');
+ ev("S.pops.pcn.bb={d:5};S.pie.dishes=S.pie.dishes.filter(x=>x.city!=='pcn');compute()");
+ assert.equal(ev('R.rev.grant'), 0, 'no dish, no grant');
+ assert.deepEqual(errors, []);
+});
+
+test('Rural Digital Pie Fund: a cut-off town is auctioned, the lowest ask wins and is paid monthly', () => {
+ const { ev, errors } = load();
+ pitcairn(ev);
+ assert.ok(J(ev, 'pieRdfCands()').includes('pcn'), 'Pitcairn on backhaul is a candidate');
+ assert.ok(!J(ev, 'pieRdfCands()').includes('akl'), 'a POP on the backbone is not');
+ ev("pieRdfOpen('pcn')");
+ assert.ok(ev('S.log[0].t').includes('Pitcairn') || ev('S.log[0].t').includes('Adamstown'), 'announced');
+ assert.equal(J(ev, 'pieRdfCands()').includes('pcn'), false, 'one auction per town');
+ // The rival asks 60%: asking 50% wins, at 50% of the reserve.
+ ev("const a=S.pie.gov.auc[0];a.riv=0.6;ACT.pieBid({id:a.id,f:0.5})");
+ assert.equal(ev('S.pie.gov.auc[0].bid'), 0.5);
+ ev('ACT.pieBid({id:S.pie.gov.auc[0].id,f:0.33})');
+ assert.equal(ev('S.pie.gov.auc[0].bid'), 0.5, 'only the offered bids');
+ const ask = ev('S.pie.gov.auc[0].ask');
+ govDays(ev, ev('PIE_RDF_DAYS'));
+ assert.equal(ev('S.pie.gov.auc.length'), 0, 'closed');
+ const w = J(ev, 'S.pie.gov.aw[0]');
+ assert.equal(w.city, 'pcn');
+ assert.equal(w.mo, Math.round(ask * 0.5));
+ ev('compute()');
+ assert.equal(ev('R.rev.gov'), w.mo, 'the subsidy is revenue');
+ assert.equal(ev('R.pie.gov.rdf'), w.mo, 'and orbit income in the books');
+ ev('S.pie.book.earned=0');
+ govDays(ev, 3);
+ assert.ok(Math.abs(ev('S.pie.book.earned') - 3 * (w.mo + ev('GRANT_SKY_MO')) / 30) < 1e-3, 'three days booked');
+ // Served well past the deadline: still paid.
+ govDays(ev, ev('PIE_RDF_DUE'));
+ assert.equal(ev('S.pie.gov.aw.length'), 1, 'kept while served');
+ assert.ok(ev("pieRdfSrv('pcn')") >= ev('PIE_RDF_NEED'));
+ assert.deepEqual(errors, []);
+});
+
+test('the rival under your ask wins; you only hear about auctions you bid in', () => {
+ const { ev, errors } = load();
+ pitcairn(ev);
+ ev("pieRdfOpen('pcn');const a=S.pie.gov.auc[0];a.riv=0.6;a.rv=0;ACT.pieBid({id:a.id,f:0.9})");
+ govDays(ev, ev('PIE_RDF_DAYS'));
+ assert.equal(ev('S.pie.gov.aw.length'), 0);
+ assert.match(ev('S.log[0].t'), /ViaSad won/);
+ ev("pieRdfOpen('pcn');S.pie.gov.auc[0].riv=0.95");
+ const n = ev('S.log.length');
+ govDays(ev, ev('PIE_RDF_DAYS'));
+ assert.equal(ev('S.pie.gov.aw.length'), 0, 'no bid, no award');
+ assert.equal(ev('S.log.length'), n, 'and no news');
+ assert.deepEqual(errors, []);
+});
+
+test('service under the minimum past the deadline: a warning, then the award is revoked and part of it clawed back', () => {
+ const { ev, errors } = load();
+ pitcairn(ev);
+ ev("pieRdfOpen('pcn');const a=S.pie.gov.auc[0];a.riv=1;ACT.pieBid({id:a.id,f:0.7})");
+ govDays(ev, ev('PIE_RDF_DAYS'));
+ const w = J(ev, 'S.pie.gov.aw[0]');
+ // The pies go to safe mode: Pitcairn is cut off. Before the deadline the fund waits.
+ ev('S.pie.safe=true;compute()');
+ assert.equal(ev("pieRdfSrv('pcn')"), 0);
+ govDays(ev, 60);
+ assert.equal(ev('S.pie.gov.aw.length'), 1, 'still building out: no check before the deadline');
+ assert.equal(ev('S.pie.gov.aw[0].k'), 0);
+ govDays(ev, 30);
+ assert.equal(ev('S.pie.gov.aw.length'), 1, 'the first bad month past the deadline is a warning');
+ assert.equal(ev('S.pie.gov.aw[0].k'), 1);
+ assert.match(ev('S.log[0].t'), /watching/);
+ ev('S.pie.book.earned=1e9');
+ govDays(ev, 30);
+ assert.equal(ev('S.pie.gov.aw.length'), 0, 'the second in a row revokes it');
+ const paid = 120 * w.mo / 30, claw = Math.round(Math.min(paid, 12 * w.mo) * ev('PIE_RDF_CLAW'));
+ // The month's subsidy was booked day by day (compute() still counted it), then the claw came off.
+ assert.equal(ev('R.pie.gov.sky'), 0, 'no satellite grant in safe mode');
+ assert.ok(Math.abs(ev('1e9-S.pie.book.earned') - (claw - w.mo)) < 2, `clawed back ${claw}`);
+ assert.match(ev('S.log[0].t'), /revoked/);
+ assert.equal(ev('S.stats.pieRdfLost'), 1);
+ ev('compute()');
+ assert.equal(ev('R.rev.gov'), 0, 'no more subsidy');
+ assert.deepEqual(errors, []);
+});
+
+test('a good month clears the warning', () => {
+ const { ev, errors } = load();
+ pitcairn(ev);
+ ev("pieRdfOpen('pcn');const a=S.pie.gov.auc[0];a.riv=1;ACT.pieBid({id:a.id,f:0.7})");
+ govDays(ev, ev('PIE_RDF_DAYS'));
+ ev('S.pie.safe=true;compute()');
+ govDays(ev, 90);
+ assert.equal(ev('S.pie.gov.aw[0].k'), 1);
+ ev('S.pie.safe=false;compute()');
+ govDays(ev, 30);
+ assert.equal(ev('S.pie.gov.aw[0].k'), 0);
+ ev('S.pie.safe=true;compute()');
+ govDays(ev, 30);
+ assert.equal(ev('S.pie.gov.aw.length'), 1, 'one bad month again: only a warning');
+ assert.deepEqual(errors, []);
+});
+
+test('Ex-Im Pie Bank: a cheap loan sized to the constellation, with space covenants', () => {
+ const { dom, ev, errors } = load();
+ sky(ev);
+ ev("S.pie.crusts.short.cohorts=[{n:100,day:S.day,las:true}];pieGovDay(S.day)");
+ const o = J(ev, 'S.pie.gov.ex');
+ assert.ok(o, 'offered once there is a factory');
+ assert.ok(J(ev, 'piePopCc()').includes(o.cc), 'by a country you have a POP in');
+ assert.ok(o.amt >= ev('PIE_EXIM_MIN') && o.amt <= ev('pieEximCap()'), `${o.amt}`);
+ assert.ok(o.apr >= 0.015 && o.apr <= 0.025, `cheap: ${o.apr}`);
+ // Bigger constellation, bigger loan, never past the cap.
+ ev("S.pie.gov.ex=null;pieCohort('short',200,true);pieGovDay(S.day)");
+ assert.ok(ev('S.pie.gov.ex.amt') > o.amt, 'grows with the pies');
+ ev("pieCohort('short',30000,true);S.pie.gov.ex=null;pieGovDay(S.day)");
+ assert.equal(ev('S.pie.gov.ex.amt'), ev('pieEximCap()'));
+ ev("S.pie.gov.ex.cc='GB'");
+ const cash = ev('S.cash'), amt = ev('S.pie.gov.ex.amt');
+ ev('ACT.pieExim()');
+ const l = J(ev, "S.loans.find(l=>l.bank==='exim')");
+ assert.ok(l, 'taken');
+ assert.equal(ev('S.cash') - cash >= amt - 1, true, 'paid out');
+ assert.deepEqual(l.covs, ['pielaunch', 'piedish']);
+ assert.equal(l.pie.cc, 'GB');
+ assert.equal(ev('S.pie.gov.ex'), null);
+ ev('pieGovDay(S.day)');
+ assert.equal(ev('S.pie.gov.ex'), null, 'one at a time');
+ ev('compute()');
+ assert.ok(ev('R.cost.loans') >= l.pay, 'billed like any loan');
+ // Launches count; the dish covenant wants a dish in Britain.
+ ev('for(const f of PIE_ON.launch)f({n:20,test:false},true)');
+ assert.equal(ev("S.loans.find(l=>l.bank==='exim').pie.flown"), 20);
+ assert.equal(ev("COVS.pielaunch.ok(S.loans.find(l=>l.bank==='exim'))"), true, 'before the deadline');
+ assert.equal(ev("COVS.piedish.ok(S.loans.find(l=>l.bank==='exim'))"), false, 'no dish in GB');
+ // The bank and Pie Control show it, on a phone.
+ ev("window.innerWidth=360;UI.started=true;$('bankBox').hidden=false;renderBank()");
+ const bank = dom.window.document.querySelector('#bankCard').textContent;
+ assert.match(bank, /Ex-Im Pie Bank/);
+ assert.match(bank, /Launch \d+ pies by .* \(20 so far\)/);
+ assert.match(bank, /Keep a pie dish in/);
+ ev("$('bankBox').hidden=true;ACT.pieGovOpen()");
+ assert.match(dom.window.document.querySelector('#modal').textContent, /Ex-Im Pie Bank/);
+ ev('closeModal()');
+ assert.deepEqual(errors, []);
+});
+
+test('a broken space covenant: the bank penalty, tighter terms and a spat in the lending country', () => {
+ const { ev, errors } = load();
+ sky(ev);
+ ev("pieGovDay(S.day);S.pie.gov.ex.cc='GB';ACT.pieExim()");
+ const L = "S.loans.find(l=>l.bank==='exim')";
+ const apr = ev(`${L}.apr`);
+ assert.equal(ev('pieChaos()'), true);
+ ev("S.pie.spat={};for(let i=0;i<26;i++){S.day++;loanTick(S.day);}");
+ assert.ok(Math.abs(ev(`${L}.apr`) - apr - ev('PIE_EXIM_PEN')) < 1e-9, 'rate up');
+ assert.equal(ev(`${L}.pie.br`), 1);
+ assert.equal(ev('S.pie.spat.home&&S.pie.spat.home.cc'), 'GB', 'no dish in Britain: "data stays home"');
+ assert.ok(ev('S.loanStrikes') >= 1, 'and the bank\'s own penalty');
+ // A dish there mends that one; missing the launch target reschedules it and Britain is cross again.
+ ev(`ACT.pieDish({city:'lon'});ACT.pieLic({cc:'GB'});S.pie.spat={};${L}.pie.by=S.day;${L}.breach=0`);
+ assert.equal(ev(`COVS.piedish.ok(${L})`), true);
+ ev('for(let i=0;i<11;i++){S.day++;loanTick(S.day);}');
+ assert.equal(ev(`${L}.pie.br`), 2);
+ assert.ok(ev(`${L}.pie.by`) > ev('S.day'), 'a new deadline');
+ assert.equal(ev(`COVS.pielaunch.ok(${L})`), true);
+ assert.equal(ev('S.pie.spat.lic&&S.pie.spat.lic.cc'), 'GB', 'landing rights questioned');
+ // Without chaos: tighter terms, no spat (rule O5).
+ ev(`S.rules.chaos='none';S.pie.spat={};${L}.pie.by=S.day;${L}.breach=0;for(let i=0;i<11;i++){S.day++;loanTick(S.day);}`);
+ assert.equal(ev(`${L}.pie.br`), 3);
+ assert.deepEqual(J(ev, 'Object.keys(S.pie.spat)'), []);
+ assert.deepEqual(errors, []);
+});
+
+test('the Gov tab fits a phone and lists the auction, the awards, Pitcairn and the bank', () => {
+ const { dom, ev, errors } = load();
+ pitcairn(ev);
+ ev("window.innerWidth=360;pieRdfOpen('pcn');S.pie.gov.aw.push({id:'w1',city:'akl',mo:5e6,start:S.day,due:S.day+90,end:S.day+1800,s:0,n:0,paid:0});UI.pieTab=null;ACT.pieGovOpen()");
+ const m = dom.window.document.querySelector('#modal');
+ assert.equal(ev("$('modal').hidden"), false);
+ assert.equal(m.querySelectorAll('[data-act=pieBid]').length, 3, 'three asks');
+ assert.match(m.textContent, /Rural Digital Pie Fund/);
+ assert.match(m.textContent, /Auckland/);
+ assert.match(m.textContent, /Pitcairn/);
+ assert.match(m.textContent, /satellite grant/);
+ assert.doesNotMatch(m.textContent, /pie_gov\.|banks\.|undefined|NaN/);
+ ev("ACT.pieBid({id:S.pie.gov.auc[0].id,f:0.7})");
+ assert.ok(dom.window.document.querySelector('#modal [data-act=pieBid].pink'), 'your bid is marked');
+ ev('closeModal()');
+ assert.deepEqual(errors, []);
+});
+
+test('saves: the fund and the bank survive a round trip, garbage is repaired, old saves load', () => {
+ const { ev, errors } = load();
+ sky(ev);
+ ev("pieRdfOpen('ams');S.pie.gov.aw.push({id:'w1',city:'bru',mo:5e6,start:S.day-10,due:S.day+80,end:S.day+1790,s:4.5,n:5,k:1,paid:1e6});pieGovDay(S.day);S.pie.gov.ex.cc='GB';ACT.pieExim()");
+ const before = J(ev, 'S.pie.gov');
+ ev('S=migrate(JSON.parse(JSON.stringify(S)))');
+ assert.deepEqual(J(ev, 'S.pie.gov'), before);
+ assert.equal(ev("S.loans.find(l=>l.bank==='exim').pie.cc"), 'GB');
+ // Garbage.
+ ev("S.pie.gov={auc:[{city:'nowhere'},{id:'x',city:'ams',ask:1e30,close:-5,riv:7,bid:0.42}],aw:'lots',ex:{cc:'XX'},told:'yes'};S.loans.find(l=>l.bank==='exim').pie={cc:'XX',n:-4};S.loans.find(l=>l.bank==='exim').covs=['golf'];S=migrate(JSON.parse(JSON.stringify(S)))");
+ const g = J(ev, 'S.pie.gov');
+ assert.equal(g.auc.length, 1);
+ assert.equal(g.auc[0].bid, 0);
+ assert.ok(g.auc[0].ask <= ev('PIE_RDF_MO*20'));
+ assert.ok(g.auc[0].riv <= 1);
+ assert.deepEqual(g.aw, []);
+ assert.equal(g.ex, null);
+ const l = J(ev, "S.loans.find(l=>l.bank==='exim')");
+ assert.equal(l.pie.cc, 'DE', 'the home country');
+ assert.equal(l.pie.n, 0);
+ assert.deepEqual(l.covs, ['pielaunch', 'piedish']);
+ // A save from before: no gov at all.
+ ev('delete S.pie.gov;S=migrate(JSON.parse(JSON.stringify(S)));pieGovDay(S.day);compute()');
+ assert.deepEqual(J(ev, 'S.pie.gov.aw'), []);
+ assert.equal(ev('R.rev.gov'), 0);
+ assert.deepEqual(errors, []);
+});
+
+test('ordinary banks never offer the Ex-Im loan', () => {
+ const { ev, errors } = load();
+ ev("ACT.start({});S.day=100;S.cash=1000;for(let i=0;i<300;i++){S.loanOffers=[];spawnLoanOffer(i%2===0);if(S.loanOffers.some(o=>o.bank==='exim'))break;}");
+ assert.equal(ev("S.loanOffers.some(o=>o.bank==='exim')"), false);
+ assert.deepEqual(errors, []);
+});
diff --git a/tests/pie-in-the-sky.test.js b/tests/pie-in-the-sky.test.js
index 29fe732..d623f89 100644
--- a/tests/pie-in-the-sky.test.js
+++ b/tests/pie-in-the-sky.test.js
@@ -273,7 +273,7 @@ test('Pie Control renders every tab on a phone', () => {
ev('window.innerWidth=360');
won(ev);
company(ev);
- for (const t of ['co', 'fly', 'dish', 'book']) {
+ for (const t of ['co', 'fly', 'dish', 'gov', 'book']) {
ev(`ACT.pieTab({t:'${t}'})`);
assert.equal(ev("$('modal').hidden"), false);
assert.ok(dom.window.document.querySelectorAll('#modalCard [data-act]').length > 2, t);
diff --git a/tests/pie-routing.test.js b/tests/pie-routing.test.js
index 2e84f38..575bbfc 100644
--- a/tests/pie-routing.test.js
+++ b/tests/pie-routing.test.js
@@ -174,7 +174,9 @@ test('orbit earnings go into the book, day by day', () => {
const { ev, errors } = load();
world(ev);
term(ev, 'pz', 'pcn');
- const mo = ev('R.pie.rev');
+ // Homes on Pitcairn online through the pies also bring the UK's satellite grant (tests/pie-gov.test.js).
+ assert.equal(ev('R.pie.gov.sky'), ev('GRANT_SKY_MO'));
+ const mo = ev('R.pie.rev+R.pie.gov.rdf+R.pie.gov.sky');
ev('for(let i=0;i<30;i++)dayTick()');
assert.ok(Math.abs(ev('S.pie.book.earned') - mo) / mo < 0.05, `${ev('S.pie.book.earned')} ≈ ${mo}`);
assert.deepEqual(errors, []);