diff --git a/docs/MP-CAPABILITY-BOUNDARY.md b/docs/MP-CAPABILITY-BOUNDARY.md index 9107cac4..cfed6a06 100644 --- a/docs/MP-CAPABILITY-BOUNDARY.md +++ b/docs/MP-CAPABILITY-BOUNDARY.md @@ -95,7 +95,10 @@ dead MP controls offline and no synthesized server state anywhere: `loadStatus` sits outside enter/refresh, so every failure keeps the last good figures without touching phase or error state, and the screen refreshes it on the reference cadence (60s while visible, plus a new turn - and foreground return). + and foreground return). The wide layout of the same read + (`?layout=full`) carries the per-turn campaign income breakdown; because + it runs the reference's enrichment queries, it is read on demand when the + funds details are opened and never polled. - World reads are public and separate from the character projection: `GET /api/countries` answers the runtime nation directory, `GET /api/country/[code]/overview-counts` answers one nation's headline @@ -103,8 +106,9 @@ dead MP controls offline and no synthesized server state anywhere: balance, unions, prime rate), `GET /api/country/[code]/states` answers that nation's regions, `GET /api/country/[code]/parties` and `GET /api/country/[code]/politicians` answer its parties and - politicians, and `GET /api/elections?country={code}&view=summary` answers - its races, and `GET /api/news` answers the world news feed. The Rust bridge pins the country code to a two-letter key, + politicians, `GET /api/country/[code]/legislature/leaders` answers its + legislature leadership, `GET /api/elections?country={code}&view=summary` + answers its races, and `GET /api/news` answers the world news feed. The Rust bridge pins the country code to a two-letter key, and the adapter refuses to send anything else. All of these loads sit outside enter/refresh: a failure keeps the last good view and never expires the session. diff --git a/docs/NAVIGATION-PARITY.md b/docs/NAVIGATION-PARITY.md index b7801ced..9caebc61 100644 --- a/docs/NAVIGATION-PARITY.md +++ b/docs/NAVIGATION-PARITY.md @@ -963,3 +963,48 @@ tests: the search fills the recipient, a failed search keeps the draft) and last-good-matches posture) plus the Rust path/allowlist assertions in `mp_session::tests::world_reads_resolve_to_pinned_paths`. No physical-iPhone evidence is claimed; #363/#436 remain open. + +## 29. MP campaign income breakdown (#510) + +The reference status bar shows the per-turn campaign income lines in the +funds details: base generation, donor bonus, office bonus, union +contribution, state and national tax, and the net per turn. Multiplayer +showed only the balance. + +Delivered: + +- A new audited read, `GET /api/client-status?layout=full`, answers the + breakdown. The Rust bridge pins the layout (the wide layout runs the + reference's enrichment queries, so it is never polled) and the transport + allowlist accepts only the two pinned layouts for that path. +- Opening the funds details reads the wide payload on demand and renders the + server's own lines: base generation, donor bonus, office bonus, union + contribution, state tax, national tax and net per turn. A figure the + server did not report reads "not reported". +- A failed wide read leaves the details and the session intact. + +Focused evidence: `src/ui/MpIncomeBreakdown510.test.tsx` (2 rendered tests: +the breakdown is read on demand and shown, a failed wide read stays +honest), `src/mp/status.test.ts` (the breakdown projection and the +last-good-view posture) and the Rust test +`mp_session::tests::full_status_read_pins_the_full_layout`. No +physical-iPhone evidence is claimed; #363/#436 remain open. + +## 30. MP nation leadership (#510) + +The reference nation page names the people who run the country. The +multiplayer nation drill-in stopped at the institutions. + +Delivered: + +- A new audited read, `GET /api/country/[code]/legislature/leaders`, + answers the nation's legislature leadership. The Rust bridge pins the + country code and the path shape. +- The nation card now names the prime minister and the opposition leader + with their party, exactly as the server reports them. A seat the server + does not publish (the speaker, for now) stays absent. + +Focused evidence: `src/ui/MpNations510.test.tsx` (the leadership rows ride +the nation drill-in), `src/mp/nations.test.ts` (the projection, the invalid +code refusal, the last-good-holders posture) and the Rust path/allowlist +assertions. No physical-iPhone evidence is claimed; #363/#436 remain open. diff --git a/src-tauri/src/mp_session.rs b/src-tauri/src/mp_session.rs index ef891e9f..dd5cab70 100644 --- a/src-tauri/src/mp_session.rs +++ b/src-tauri/src/mp_session.rs @@ -112,6 +112,12 @@ pub enum MpFetchOp { /// influence and favorability the footer shows, and skips the /// corporation/election/income enrichment the wider layouts run. ClientStatus, + /// The full status read; GET /api/client-status?layout=full + /// (requireBasicAuth, 401 signed out). Read on demand when the + /// player asks for the per-turn campaign income breakdown, which the + /// minimal layout does not carry. The wider layout runs the + /// reference's enrichment queries, so it is never polled. + ClientStatusFull, /// Turn/year/processing/countdown; public but fresher via the session. TurnStatus, /// Players active within the last hour; public, no session required. @@ -183,6 +189,10 @@ pub enum MpFetchOp { /// The nation's politicians; GET /api/country/[code]/politicians /// (public, no auth, 400 on an invalid country). CountryPoliticians, + /// The nation's legislature leadership; GET + /// /api/country/[code]/legislature/leaders (public, no auth, 404 on + /// an invalid country). + CountryLeaders, /// A nation's election list; GET /api/elections?country={code}&view= /// summary (public with optional auth, 400 on an invalid country). /// The country code is a two-letter COUNTRY_CONFIGS key; see @@ -205,6 +215,7 @@ impl MpFetchOp { "savings-accounts" => Some(Self::SavingsAccounts), "client-nav" => Some(Self::ClientNav), "client-status" => Some(Self::ClientStatus), + "client-status-full" => Some(Self::ClientStatusFull), "turn-status" => Some(Self::TurnStatus), "players-online" => Some(Self::PlayersOnline), "game-time" => Some(Self::GameTime), @@ -222,6 +233,7 @@ impl MpFetchOp { "country-states" => Some(Self::CountryStates), "country-parties" => Some(Self::CountryParties), "country-politicians" => Some(Self::CountryPoliticians), + "country-leaders" => Some(Self::CountryLeaders), "election-list" => Some(Self::ElectionList), "news-feed" => Some(Self::NewsFeed), "character-search" => Some(Self::CharacterSearch), @@ -236,6 +248,7 @@ impl MpFetchOp { Self::SavingsAccounts => "/api/character/savings", Self::ClientNav => "/api/client-nav", Self::ClientStatus => "/api/client-status", + Self::ClientStatusFull => "/api/client-status", Self::TurnStatus => "/api/game/turn/status", Self::PlayersOnline => "/api/players/online", Self::GameTime => "/api/game-time", @@ -253,6 +266,7 @@ impl MpFetchOp { Self::CountryStates => "/api/country", Self::CountryParties => "/api/country", Self::CountryPoliticians => "/api/country", + Self::CountryLeaders => "/api/country", Self::ElectionList => "/api/elections", Self::NewsFeed => "/api/news", Self::CharacterSearch => "/api/characters/search", @@ -612,14 +626,19 @@ fn fetch_path_and_query( offset: Option, ) -> Result { match op { - MpFetchOp::ClientStatus => { + MpFetchOp::ClientStatus | MpFetchOp::ClientStatusFull => { if limit.is_some() || offset.is_some() { return Err(error::UNSUPPORTED_OP.to_string()); } // The layout is pinned, never caller-supplied: the minimal // layout answers the footer scalars without the wide - // enrichment queries. - Ok(format!("{}?layout=minimal", op.path())) + // enrichment queries, and the full layout is read on demand + // for the campaign income breakdown. + let layout = match op { + MpFetchOp::ClientStatus => "minimal", + _ => "full", + }; + Ok(format!("{}?layout={}", op.path(), layout)) } MpFetchOp::NewsFeed => { let limit = limit.ok_or_else(|| error::BAD_ARG.to_string())?; @@ -793,6 +812,30 @@ fn is_country_parties_path(path: &str) -> bool { is_country_suffix_path(path, "parties") } +/// Build the exact nation legislature leadership request path from a +/// validated country key. +fn fetch_country_leaders_path(country_code: &str) -> Result { + if !is_country_code(country_code) { + return Err(error::BAD_ARG.to_string()); + } + Ok(format!( + "{}/{}/legislature/leaders", + MpFetchOp::CountryLeaders.path(), + country_code.to_ascii_uppercase() + )) +} + +/// True for the pinned nation legislature leadership path shape. +fn is_country_leaders_path(path: &str) -> bool { + let Some(rest) = path.strip_prefix("/api/country/") else { + return false; + }; + let Some(code) = rest.strip_suffix("/legislature/leaders") else { + return false; + }; + is_country_code(code) +} + /// True for the pinned nation politicians path shape. fn is_country_politicians_path(path: &str) -> bool { is_country_suffix_path(path, "politicians") @@ -1363,8 +1406,10 @@ fn is_allowlisted_call(method: &str, path_and_query: &str) -> bool { | ("GET", "/api/players/online") | ("GET", "/api/admin/maintenance") | ("GET", "/api/game-time") => query.is_none(), - // The status read only ever runs with the pinned minimal layout. - ("GET", "/api/client-status") => matches!(query, Some("layout=minimal")), + // The status read only ever runs with a pinned layout. + ("GET", "/api/client-status") => { + matches!(query, Some("layout=minimal") | Some("layout=full")) + } ("GET", "/api/countries") => query.is_none(), ("GET", "/api/characters/search") => match query { Some(query) => is_character_search_pair(query), @@ -1396,7 +1441,8 @@ fn is_allowlisted_call(method: &str, path_and_query: &str) -> bool { || is_country_overview_path(path) || is_country_states_path(path) || is_country_parties_path(path) - || is_country_politicians_path(path)) + || is_country_politicians_path(path) + || is_country_leaders_path(path)) } ("POST", "/api/actions/execute") | ("PATCH", "/api/notifications") => query.is_none(), ("PUT", "/api/notifications/preferences") => query.is_none(), @@ -2162,6 +2208,44 @@ pub async fn mp_session_fetch( .ok_or_else(|| error::BAD_ARG.to_string())?; fetch_country_politicians_path(country)? } + MpFetchOp::ClientStatusFull => { + if limit.is_some() + || offset.is_some() + || detail.election_id.is_some() + || detail.corporation_id.is_some() + || detail.union_id.is_some() + || detail.cabinet_country_code.is_some() + || detail.cabinet_position_id.is_some() + || detail.governor_country_code.is_some() + || detail.governor_state_id.is_some() + || detail.country_code.is_some() + || detail.search_query.is_some() + { + return Err(error::UNSUPPORTED_OP.to_string()); + } + fetch_path_and_query(op, limit, offset)? + } + MpFetchOp::CountryLeaders => { + if limit.is_some() + || offset.is_some() + || detail.election_id.is_some() + || detail.corporation_id.is_some() + || detail.union_id.is_some() + || detail.cabinet_country_code.is_some() + || detail.cabinet_position_id.is_some() + || detail.governor_country_code.is_some() + || detail.governor_state_id.is_some() + || detail.country_code.is_some() + || detail.search_query.is_some() + { + return Err(error::UNSUPPORTED_OP.to_string()); + } + let country = detail + .country_code + .as_deref() + .ok_or_else(|| error::BAD_ARG.to_string())?; + fetch_country_leaders_path(country)? + } MpFetchOp::CharacterSearch => { if limit.is_some() || offset.is_some() @@ -2310,9 +2394,12 @@ mod tests { "/api/client-status?layout=minimal" )); assert!(!is_allowlisted_call("GET", "/api/client-status")); + // The full layout is allowlisted too, but only for the on-demand + // income breakdown read. + assert!(is_allowlisted_call("GET", "/api/client-status?layout=full")); assert!(!is_allowlisted_call( "GET", - "/api/client-status?layout=full" + "/api/client-status?layout=wide" )); assert!(!is_allowlisted_call( "GET", @@ -2324,6 +2411,27 @@ mod tests { )); } + #[test] + fn full_status_read_pins_the_full_layout() { + assert_eq!( + MpFetchOp::from_id("client-status-full"), + Some(MpFetchOp::ClientStatusFull) + ); + assert_eq!( + fetch_path_and_query(MpFetchOp::ClientStatusFull, None, None).unwrap(), + "/api/client-status?layout=full" + ); + assert!(!is_allowlisted_call( + "GET", + "/api/client-status?layout=full&x=1" + )); + assert!(!is_allowlisted_call( + "POST", + "/api/client-status?layout=full" + )); + assert!(fetch_path_and_query(MpFetchOp::ClientStatusFull, Some(5), None).is_err()); + } + #[test] fn world_reads_resolve_to_pinned_paths() { assert_eq!(MpFetchOp::from_id("countries"), Some(MpFetchOp::Countries)); @@ -2408,6 +2516,32 @@ mod tests { )); assert!(fetch_country_politicians_path("").is_err()); + assert_eq!( + MpFetchOp::from_id("country-leaders"), + Some(MpFetchOp::CountryLeaders) + ); + assert_eq!( + fetch_country_leaders_path("uk").unwrap(), + "/api/country/UK/legislature/leaders" + ); + assert!(is_allowlisted_call( + "GET", + "/api/country/UK/legislature/leaders" + )); + assert!(!is_allowlisted_call( + "GET", + "/api/country/UKA/legislature/leaders" + )); + assert!(!is_allowlisted_call( + "GET", + "/api/country/UK/legislature/leaders?x=1" + )); + assert!(!is_allowlisted_call( + "GET", + "/api/country/UK/legislature/leader" + )); + assert!(fetch_country_leaders_path("u k").is_err()); + assert_eq!( MpFetchOp::from_id("election-list"), Some(MpFetchOp::ElectionList) diff --git a/src/mp/adapter.test.ts b/src/mp/adapter.test.ts index afa0efee..53b4bdab 100644 --- a/src/mp/adapter.test.ts +++ b/src/mp/adapter.test.ts @@ -206,6 +206,7 @@ describe("MpModeSession enter", () => { nationRegions: null, nationParties: null, nationPoliticians: null, + nationLeaders: null, electionList: null, newsFeed: null, characterSearch: null, diff --git a/src/mp/adapter.ts b/src/mp/adapter.ts index df9f7d4e..d5f19a5d 100644 --- a/src/mp/adapter.ts +++ b/src/mp/adapter.ts @@ -6,6 +6,7 @@ import { parseCharacterSearch, parseClientStatus, parseCountries, + parseCountryLeaders, parseCountryOverview, parseCountryParties, parseCountryPoliticians, @@ -54,6 +55,7 @@ import { type MpRegionView, type MpNationPartyView, type MpNationPoliticianView, + type MpNationLeadersView, type MpNewsPostView, type MpCharacterSearchResult, type MpUnionDetailView, @@ -144,6 +146,11 @@ export interface MpSnapshot { * /api/country/[code]/politicians. */ nationPoliticians: MpNationPoliticianView[] | null; + /** + * The selected nation's legislature leadership, from + * /api/country/[code]/legislature/leaders. Loaded on demand. + */ + nationLeaders: MpNationLeadersView | null; /** * A nation's election list, from * /api/elections?country={code}&view=summary. Loaded on demand. @@ -191,6 +198,7 @@ const INITIAL_SNAPSHOT: MpSnapshot = { nationRegions: null, nationParties: null, nationPoliticians: null, + nationLeaders: null, electionList: null, newsFeed: null, characterSearch: null, @@ -213,9 +221,9 @@ export const MP_MAIL_LIMIT = 50; function emptyAuthed(): Pick< MpSnapshot, - "character" | "savings" | "turn" | "capabilities" | "electionDetail" | "corporationDetail" | "unionDetail" | "cabinetDetail" | "governorDetail" | "inbox" | "mailInbox" | "mailSent" | "presence" | "status" | "nations" | "nationOverview" | "nationRegions" | "nationParties" | "nationPoliticians" | "electionList" | "newsFeed" | "characterSearch" + "character" | "savings" | "turn" | "capabilities" | "electionDetail" | "corporationDetail" | "unionDetail" | "cabinetDetail" | "governorDetail" | "inbox" | "mailInbox" | "mailSent" | "presence" | "status" | "nations" | "nationOverview" | "nationRegions" | "nationParties" | "nationPoliticians" | "nationLeaders" | "electionList" | "newsFeed" | "characterSearch" > { - return { character: null, savings: null, turn: null, capabilities: null, electionDetail: null, corporationDetail: null, unionDetail: null, cabinetDetail: null, governorDetail: null, inbox: null, mailInbox: null, mailSent: null, presence: null, status: null, nations: null, nationOverview: null, nationRegions: null, nationParties: null, nationPoliticians: null, electionList: null, newsFeed: null, characterSearch: null }; + return { character: null, savings: null, turn: null, capabilities: null, electionDetail: null, corporationDetail: null, unionDetail: null, cabinetDetail: null, governorDetail: null, inbox: null, mailInbox: null, mailSent: null, presence: null, status: null, nations: null, nationOverview: null, nationRegions: null, nationParties: null, nationPoliticians: null, nationLeaders: null, electionList: null, newsFeed: null, characterSearch: null }; } export class MpModeSession { @@ -648,6 +656,37 @@ export class MpModeSession { } } + /** + * Read the legislature leadership of one nation (#510 world + * destinations). GET /api/country/[code]/legislature/leaders is public; + * the code is checked here and again by the Rust bridge. A failed read + * keeps the previous holders and never fails the session. Never throws. + */ + async loadCountryLeaders(code: unknown): Promise { + if (!isCountryCode(code)) return this.get(); + try { + const result = await mpFetch( + this.host, + "country-leaders", + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + code, + ); + if (result.kind !== "ok") return this.get(); + const nationLeaders = parseCountryLeaders(result.bodyText); + if (!nationLeaders) return this.get(); + return this.set({ nationLeaders }); + } catch { + return this.get(); + } + } + /** * Read the political parties of one nation (#510 world destinations). GET * /api/country/[code]/parties is public; the code is checked here and @@ -710,6 +749,26 @@ export class MpModeSession { } } + /** + * Read the full status payload (#510 campaign income breakdown). The wide + * layout carries the per-turn campaign income lines the minimal layout + * omits, at the cost of the reference's enrichment queries, so it is read + * on demand and never polled. Every failure keeps the last good view and + * never fails the session. Never throws. + */ + async loadFullStatus(): Promise { + if (!this.snapshot.userId || this.snapshot.phase !== "ready") return this.get(); + try { + const result = await mpFetch(this.host, "client-status-full"); + if (result.kind !== "ok") return this.get(); + const status = parseClientStatus(result.bodyText); + if (!status) return this.get(); + return this.set({ status }); + } catch { + return this.get(); + } + } + /** * Search characters by name for the mail recipient picker (#510). The * read is public; the fragment is validated here and again by the Rust diff --git a/src/mp/endpoints.ts b/src/mp/endpoints.ts index 9e96ba17..5ca88dfb 100644 --- a/src/mp/endpoints.ts +++ b/src/mp/endpoints.ts @@ -99,6 +99,16 @@ * {results:[{id,userId,name,username,discordUsername,party,homeState, * avatarUrl,currentOffice}]}. The route ignores queries shorter than two * characters; the bridge pins the limit at 10 and encodes the fragment. + * - client-status-full GET /api/client-status?layout=full + * requireBasicAuth; 401 signed out. The same read in its wide layout: + * it adds the per-turn campaign income breakdown the minimal layout omits, + * at the cost of the reference's enrichment queries, so Native reads it + * on demand (when the funds details are opened) and never polls it. + * - country-leaders GET /api/country/[code]/legislature/leaders + * public, no auth; 404 on an invalid country. The nation's legislature + * leadership (AHDGame src/app/api/country/[code]/legislature/leaders/ + * route.ts): 200 {primeMinister:{characterId,characterName,party,since, + * avatarUrl}|null, oppositionLeader:{...}|null, speaker:null}. * - turn-status /api/game/turn/status public; 404 uninitialized * {singleplayer,currentTurn,currentYear,startingYear,preset, * preIterationTurns,preIterationActive,isActive,isProcessing, @@ -373,6 +383,7 @@ export type MpFetchOpId = | "savings-accounts" | "client-nav" | "client-status" + | "client-status-full" | "turn-status" | "players-online" | "game-time" @@ -390,6 +401,7 @@ export type MpFetchOpId = | "country-states" | "country-parties" | "country-politicians" + | "country-leaders" | "election-list" | "news-feed" | "character-search"; diff --git a/src/mp/nations.test.ts b/src/mp/nations.test.ts index 1d923faa..02efaa05 100644 --- a/src/mp/nations.test.ts +++ b/src/mp/nations.test.ts @@ -331,6 +331,51 @@ describe("MpModeSession loadElectionList", () => { }); }); +describe("MpModeSession loadCountryLeaders", () => { + const leaders = JSON.stringify({ + primeMinister: { + characterId: "507f1f77bcf86cd799439012", + sequentialId: 4, + characterName: "Bo", + party: "Labour Party", + since: "2026-01-01T00:00:00.000Z", + avatarUrl: null, + }, + oppositionLeader: null, + speaker: null, + }); + + it("projects the nation's legislature leadership", async () => { + const { host, calls } = scriptedHost(enterScripts({ "country-leaders": [leaders] })); + const session = new MpModeSession(host); + await session.enter(); + const snapshot = await session.loadCountryLeaders("UK"); + expect(snapshot.nationLeaders?.primeMinister).toMatchObject({ + name: "Bo", + party: "Labour Party", + }); + expect(snapshot.nationLeaders?.oppositionLeader).toBeNull(); + expect(snapshot.phase).toBe("ready"); + expect(calls.filter((call) => call === "fetch:country-leaders")).toHaveLength(1); + }); + + it("never sends an invalid country code and keeps the last good holders", async () => { + const { host, calls } = scriptedHost( + enterScripts({ "country-leaders": [leaders, { reject: "remote-error:404:Not found" }] }), + ); + const session = new MpModeSession(host); + await session.enter(); + const rejected = await session.loadCountryLeaders("uk"); + expect(rejected.nationLeaders).toBeNull(); + expect(calls.filter((call) => call === "fetch:country-leaders")).toHaveLength(0); + + await session.loadCountryLeaders("UK"); + const failed = await session.loadCountryLeaders("UK"); + expect(failed.nationLeaders?.primeMinister?.name).toBe("Bo"); + expect(failed.phase).toBe("ready"); + }); +}); + describe("MpModeSession loadCountryParties and loadCountryPoliticians", () => { const parties = JSON.stringify({ parties: [ diff --git a/src/mp/status.test.ts b/src/mp/status.test.ts index c190c4b1..8ad73eac 100644 --- a/src/mp/status.test.ts +++ b/src/mp/status.test.ts @@ -78,6 +78,64 @@ function enterScripts(extra?: Record> }; } +describe("MpModeSession loadFullStatus", () => { + const full = JSON.stringify({ + name: "Ada", + actions: 3, + funds: 1200, + cashOnHand: 1000, + homeCurrency: "USD", + campaignIncomeBreakdown: { + populationTier: "large", + baseGen: 500, + donorBonus: 120, + officeBonus: 80, + unionContribution: 40, + stateTax: 60, + nationalTax: 90, + totalTax: 150, + netPerTurn: 590, + }, + }); + + it("projects the per-turn campaign income lines", async () => { + const { host, calls } = scriptedHost( + enterScripts({ "client-status-full": [full] }), + ); + const session = new MpModeSession(host); + await session.enter(); + const snapshot = await session.loadFullStatus(); + expect(snapshot.status?.campaignIncomeBreakdown?.netPerTurn).toBe(590); + expect(snapshot.phase).toBe("ready"); + expect(snapshot.error).toBeNull(); + expect(calls.filter((call) => call === "fetch:client-status-full")).toHaveLength(1); + }); + + it("keeps the last good view when the wide read fails", async () => { + const { host } = scriptedHost( + enterScripts({ + "client-status-full": [full, { reject: "remote-error:500:Server error" }], + }), + ); + const session = new MpModeSession(host); + await session.enter(); + await session.loadFullStatus(); + const snapshot = await session.loadFullStatus(); + expect(snapshot.status?.campaignIncomeBreakdown?.netPerTurn).toBe(590); + expect(snapshot.phase).toBe("ready"); + expect(snapshot.error).toBeNull(); + }); + + it("does nothing without a signed-in session", async () => { + const { host, calls } = scriptedHost({ fetch: {} }); + const session = new MpModeSession(host); + const snapshot = await session.loadFullStatus(); + expect(snapshot.status).toBeNull(); + expect(snapshot.phase).toBe("idle"); + expect(calls).toEqual([]); + }); +}); + describe("MpModeSession loadStatus", () => { it("projects the status scalars and keeps the loaded session intact", async () => { const { host, calls } = scriptedHost( diff --git a/src/mp/validators.test.ts b/src/mp/validators.test.ts index 272b7170..190ae781 100644 --- a/src/mp/validators.test.ts +++ b/src/mp/validators.test.ts @@ -13,6 +13,7 @@ import { parseClientNav, parseClientStatus, parseCountries, + parseCountryLeaders, parseCountryOverview, parseCountryParties, parseCountryPoliticians, @@ -371,6 +372,7 @@ describe("parseClientStatus", () => { donorBaseLevel: 2, politicalInfluence: 61, favorability: 55, + campaignIncomeBreakdown: null, }); }); @@ -401,6 +403,47 @@ describe("parseClientStatus", () => { }); }); +describe("parseClientStatus with the campaign income breakdown", () => { + it("projects the per-turn income lines the wide layout carries", () => { + const view = parseClientStatus( + JSON.stringify({ + name: "Ada", + actions: 3, + funds: 1200, + cashOnHand: 1000, + homeCurrency: "USD", + campaignIncomeBreakdown: { + populationTier: "large", + baseGen: 500, + donorBonus: 120, + officeBonus: 80, + unionContribution: 40, + stateTax: 60, + nationalTax: 90, + totalTax: 150, + netPerTurn: 590, + }, + }), + ); + expect(view?.campaignIncomeBreakdown).toEqual({ + populationTier: "large", + baseGen: 500, + donorBonus: 120, + officeBonus: 80, + unionContribution: 40, + stateTax: 60, + nationalTax: 90, + totalTax: 150, + netPerTurn: 590, + }); + }); + + it("leaves the breakdown absent on the minimal layout", () => { + const view = parseClientStatus(JSON.stringify({ name: "Ada", actions: 3, funds: 1200 })); + expect(view?.campaignIncomeBreakdown).toBeNull(); + }); +}); + describe("parseCountries", () => { const full = () => JSON.stringify({ @@ -473,6 +516,41 @@ describe("parseCountryStates", () => { }); }); +describe("parseCountryLeaders", () => { + it("projects the nation's legislature leadership", () => { + expect( + parseCountryLeaders( + JSON.stringify({ + primeMinister: { + characterId: "507f1f77bcf86cd799439012", + sequentialId: 4, + characterName: "Bo", + party: "Labour Party", + since: "2026-01-01T00:00:00.000Z", + avatarUrl: null, + }, + oppositionLeader: null, + speaker: null, + }), + ), + ).toEqual({ + primeMinister: { + characterId: "507f1f77bcf86cd799439012", + name: "Bo", + party: "Labour Party", + since: "2026-01-01T00:00:00.000Z", + }, + oppositionLeader: null, + speaker: null, + }); + }); + + it("fails closed on an error envelope", () => { + expect(parseCountryLeaders(JSON.stringify({ error: "Invalid country code" }))).toBeNull(); + expect(parseCountryLeaders("not json")).toBeNull(); + }); +}); + describe("parseCountryParties", () => { it("projects the nation parties", () => { expect( diff --git a/src/mp/validators.ts b/src/mp/validators.ts index a1565bf2..340f056e 100644 --- a/src/mp/validators.ts +++ b/src/mp/validators.ts @@ -481,6 +481,27 @@ export interface MpStatusView { donorBaseLevel: number | null; politicalInfluence: number | null; favorability: number | null; + /** + * The per-turn campaign income breakdown. The minimal status layout does + * not carry it, so it is null until the full layout is read on demand. + */ + campaignIncomeBreakdown: MpCampaignIncomeBreakdown | null; +} + +/** + * The reference's per-turn campaign income lines (AHDGame + * src/app/api/client-status/route.ts). Every figure is the server's own. + */ +export interface MpCampaignIncomeBreakdown { + populationTier: string | null; + baseGen: number | null; + donorBonus: number | null; + officeBonus: number | null; + unionContribution: number | null; + stateTax: number | null; + nationalTax: number | null; + totalTax: number | null; + netPerTurn: number | null; } function statusNumber(value: unknown): number | null { @@ -510,6 +531,7 @@ export function parseClientStatus(bodyText: string): MpStatusView | null { const politicalInfluence = statusNumber(record.politicalInfluence); const favorability = statusNumber(record.favorability); const homeCurrency = asTrimmedString(record.homeCurrency ?? null); + const breakdown = asRecord(record.campaignIncomeBreakdown); const scalars = [ actions, actionCap, @@ -535,6 +557,19 @@ export function parseClientStatus(bodyText: string): MpStatusView | null { donorBaseLevel, politicalInfluence, favorability, + campaignIncomeBreakdown: breakdown + ? { + populationTier: asTrimmedString(breakdown.populationTier ?? null), + baseGen: statusNumber(breakdown.baseGen), + donorBonus: statusNumber(breakdown.donorBonus), + officeBonus: statusNumber(breakdown.officeBonus), + unionContribution: statusNumber(breakdown.unionContribution), + stateTax: statusNumber(breakdown.stateTax), + nationalTax: statusNumber(breakdown.nationalTax), + totalTax: statusNumber(breakdown.totalTax), + netPerTurn: statusNumber(breakdown.netPerTurn), + } + : null, }; } @@ -687,6 +722,52 @@ export function parseCountryStates(bodyText: string): MpRegionView[] | null { return regions; } +/** + * One office holder of a nation's legislature, from + * GET /api/country/[code]/legislature/leaders. + */ +export interface MpNationLeaderView { + characterId: string | null; + name: string | null; + party: string | null; + since: string | null; +} + +export interface MpNationLeadersView { + primeMinister: MpNationLeaderView | null; + oppositionLeader: MpNationLeaderView | null; + speaker: MpNationLeaderView | null; +} + +function projectNationLeader(value: unknown): MpNationLeaderView | null { + const item = asRecord(value); + if (!item) return null; + const name = asTrimmedString(item.characterName ?? null); + if (!name) return null; + return { + characterId: asTrimmedString(item.characterId ?? null), + name, + party: asTrimmedString(item.party ?? null), + since: asTrimmedString(item.since ?? null), + }; +} + +/** + * country-leaders: the nation's legislature leadership. A holder without a + * name is treated as absent, and the speaker is null while the server does + * not publish one. + */ +export function parseCountryLeaders(bodyText: string): MpNationLeadersView | null { + const record = asRecord(parseJsonBody(bodyText)); + if (!record) return null; + if (asTrimmedString(record.error ?? null)) return null; + return { + primeMinister: projectNationLeader(record.primeMinister), + oppositionLeader: projectNationLeader(record.oppositionLeader), + speaker: projectNationLeader(record.speaker), + }; +} + /** * One political party of a nation, from * GET /api/country/[code]/parties. diff --git a/src/ui/MpIncomeBreakdown510.test.tsx b/src/ui/MpIncomeBreakdown510.test.tsx new file mode 100644 index 00000000..bd6e5030 --- /dev/null +++ b/src/ui/MpIncomeBreakdown510.test.tsx @@ -0,0 +1,147 @@ +import { describe, expect, it, vi, afterEach } from "vitest"; +import { act, render, screen, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { MpModeScreen } from "./MpModeScreen"; +import type { MpBridgeHost } from "../mp/bridge"; + +/** + * MP campaign income breakdown (#510). The reference status bar shows the + * per-turn campaign income lines in the funds details. The minimal status + * layout does not carry them, so Native reads the wide layout on demand + * when the funds details are opened - and never polls it. + */ +const USER = "507f1f77bcf86cd799439011"; + +const probe = JSON.stringify({ active: true, sub: USER, username: "Ada" }); +const me = JSON.stringify({ + character: { _id: "c1", name: "Ada", party: "Labor", homeState: "CA", cashOnHand: 1000, actions: 3, countryId: "US" }, + corporation: null, +}); +const turn = JSON.stringify({ currentTurn: 12, currentYear: 1953, startingYear: 1953, isActive: true, isProcessing: false, nextScheduledTurn: null }); +const inbox = JSON.stringify({ notifications: [], unreadCount: 0, total: 0, hasMore: false }); +const emptyMailInbox = JSON.stringify({ mails: [], unreadCount: 0, total: 0, hasMore: false }); +const emptyMailSent = JSON.stringify({ mails: [], total: 0, hasMore: false }); +const caps = JSON.stringify({ user: null, hasCharacter: false }); +const status = JSON.stringify({ name: "Ada", actions: 3, funds: 1200, cashOnHand: 1000, homeCurrency: "USD" }); +const fullStatus = JSON.stringify({ + name: "Ada", + actions: 3, + actionCap: 5, + funds: 1200, + cashOnHand: 1000, + homeCurrency: "USD", + campaignIncomeBreakdown: { + populationTier: "large", + baseGen: 500, + donorBonus: 120, + officeBonus: 80, + unionContribution: 40, + stateTax: 60, + nationalTax: 90, + totalTax: 150, + netPerTurn: 590, + }, +}); + +afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); +}); + +function fakeHost(script: { fetch?: Record> }): { + host: MpBridgeHost; + calls: string[]; +} { + const calls: string[] = []; + const queues = new Map>(); + for (const [op, items] of Object.entries(script.fetch ?? {})) queues.set(`fetch:${op}`, [...items]); + return { + calls, + host: { + fetch: async (op: string) => { + calls.push(`fetch:${op}`); + const item = queues.get(`fetch:${op}`)?.shift(); + if (typeof item === "string") return item; + if (item) throw new Error(item.reject); + if (op === "client-nav") return caps; + throw new Error(`unexpected call fetch:${op}`); + }, + mutate: async () => { + throw new Error("unexpected mutate"); + }, + beginSignIn: async () => {}, + }, + }; +} + +async function settleMount() { + await act(async () => { + for (let i = 0; i < 200; i += 1) { + await Promise.resolve(); + } + }); +} + +describe("MpModeScreen campaign income breakdown", () => { + it("reads the wide status on demand when the funds details open", async () => { + const { host, calls } = fakeHost({ + fetch: { + "auth-session": [probe], + "character-me": [me], + "turn-status": [turn], + notifications: [inbox], + "mail-inbox": [emptyMailInbox], + "mail-sent": [emptyMailSent], + "client-status": [status], + "client-status-full": [fullStatus], + }, + }); + render( {}} />); + await settleMount(); + + const footer = within(screen.getByRole("contentinfo", { name: "Multiplayer navigation" })); + await userEvent.click(footer.getByRole("button", { name: "Campaign funds: 1,200 USD" })); + await act(async () => { + for (let i = 0; i < 200; i += 1) { + await Promise.resolve(); + } + }); + + const details = screen.getByRole("dialog", { name: "Campaign funds details" }); + const lines = within(details).getByRole("list", { name: "Campaign income per turn" }); + expect(within(lines).getByText(/Base generation: 500 USD/)).toBeInTheDocument(); + expect(within(lines).getByText(/Donor bonus: 120 USD/)).toBeInTheDocument(); + expect(within(lines).getByText(/Net per turn: 590 USD/)).toBeInTheDocument(); + expect(calls).toContain("fetch:client-status-full"); + }); + + it("keeps the details honest when the wide read fails", async () => { + const { host } = fakeHost({ + fetch: { + "auth-session": [probe], + "character-me": [me], + "turn-status": [turn], + notifications: [inbox], + "mail-inbox": [emptyMailInbox], + "mail-sent": [emptyMailSent], + "client-status": [status], + "client-status-full": [{ reject: "remote-error:500:Server error" }], + }, + }); + render( {}} />); + await settleMount(); + + const footer = within(screen.getByRole("contentinfo", { name: "Multiplayer navigation" })); + await userEvent.click(footer.getByRole("button", { name: "Campaign funds: 1,200 USD" })); + await act(async () => { + for (let i = 0; i < 200; i += 1) { + await Promise.resolve(); + } + }); + + const details = screen.getByRole("dialog", { name: "Campaign funds details" }); + expect(within(details).getByText(/Campaign funds: 1,200 USD/)).toBeInTheDocument(); + expect(within(details).queryByRole("list", { name: "Campaign income per turn" })).toBeNull(); + expect(screen.getByText("Playing as Ada")).toBeInTheDocument(); + }); +}); diff --git a/src/ui/MpModeScreen.tsx b/src/ui/MpModeScreen.tsx index 64b2698c..51fe6d80 100644 --- a/src/ui/MpModeScreen.tsx +++ b/src/ui/MpModeScreen.tsx @@ -81,6 +81,7 @@ const IDLE: MpSnapshot = { nationRegions: null, nationParties: null, nationPoliticians: null, + nationLeaders: null, electionList: null, newsFeed: null, characterSearch: null, @@ -511,6 +512,18 @@ export function MpModeScreen({ host, onAsk, askContent, onExit, preferences, onP }); }, [activeSection, snapshot.nations]); + /* Open a resource's details. The funds breakdown lives in the wide + * status layout, so opening the funds details reads it on demand + * instead of polling the heavier payload. */ + function openResourceDetails(id: string) { + setOpenResource(openResource === id ? null : id); + if (id === "funds" && !snapshot.status?.campaignIncomeBreakdown) { + void sessionRef.current!.loadFullStatus().then((next) => { + setSnapshot(next); + }); + } + } + /* Open one allowlisted support destination. A refused open reports * honestly instead of leaving a dead button behind. */ async function openSupport(destination: SupportDestination) { @@ -678,10 +691,13 @@ export function MpModeScreen({ host, onAsk, askContent, onExit, preferences, onP // drill-in; a failed sibling read keeps the nation's figures. const withRegions = await s.loadCountryRegions(target); const withParties = await s.loadCountryParties(target); - return s.loadCountryPoliticians(target).then((withPoliticians) => ({ - ...withPoliticians, + const withPoliticians = await s.loadCountryPoliticians(target); + const withLeaders = await s.loadCountryLeaders(target); + return { + ...withLeaders, nationRegions: withParties.nationRegions ?? withRegions.nationRegions, - })); + nationPoliticians: withPoliticians.nationPoliticians, + }; }).then((next) => { if (next?.nationOverview) { setNationSelected(target); @@ -891,6 +907,7 @@ export function MpModeScreen({ host, onAsk, askContent, onExit, preferences, onP const recipientMatches = snapshot.characterSearch ?? []; const nationParties = selectedNation ? snapshot.nationParties : null; const nationPoliticians = selectedNation ? snapshot.nationPoliticians : null; + const nationLeaders = selectedNation ? snapshot.nationLeaders : null; const homeCountryId = snapshot.character?.countryId ?? snapshot.capabilities?.characterCountryId ?? null; const turnFounding = snapshot.turn?.preIterationActive === true; /* Footer resource parity: the SP footer reads campaign funds from the same @@ -908,6 +925,10 @@ export function MpModeScreen({ host, onAsk, askContent, onExit, preferences, onP const statusFavorability = snapshot.status?.favorability ?? null; const statusCurrency = snapshot.status?.homeCurrency ?? null; const moneyLabel = (value: number) => (statusCurrency ? `${value.toLocaleString("en-US")} ${statusCurrency}` : value.toLocaleString("en-US")); + /* The campaign income lines the server reported, or an honest "not + * reported" when the figure is absent. */ + const incomeBreakdown = snapshot.status?.campaignIncomeBreakdown ?? null; + const incomeLine = (value: number | null) => (value === null ? "not reported" : moneyLabel(value)); const visibleElection = !needsSession && electionOpen ? snapshot.electionDetail : null; const visibleCorporation = !needsSession && corporationOpen ? snapshot.corporationDetail : null; @@ -1442,6 +1463,8 @@ export function MpModeScreen({ host, onAsk, askContent, onExit, preferences, onP {selectedNation.lowerChamberName && (<>
Lower chamber
{selectedNation.lowerChamberName}
)} {selectedNation.upperChamberName && (<>
Upper chamber
{selectedNation.upperChamberName}
)}
Central bank
{selectedNation.centralBankName ?? "Not reported"}
+ {nationLeaders?.primeMinister && (<>
Prime minister
{nationLeaders.primeMinister.name}{nationLeaders.primeMinister.party ? " · " + nationLeaders.primeMinister.party : ""}
)} + {nationLeaders?.oppositionLeader && (<>
Opposition leader
{nationLeaders.oppositionLeader.name}{nationLeaders.oppositionLeader.party ? " · " + nationLeaders.oppositionLeader.party : ""}
)} {selectedNation.executiveTitle && (<>
Executive
{selectedNation.executiveTitle}
)} {nationOverview && (<>
GDP
{nationOverview.gdpMillions !== null ? "$" + nationOverview.gdpMillions.toLocaleString("en-US") + "M" : "Not reported"}
@@ -2085,19 +2108,19 @@ export function MpModeScreen({ host, onAsk, askContent, onExit, preferences, onP {snapshot.presence && {snapshot.presence.online} online} } {snapshot.character &&
- {statusActions !== null && } - {statusFunds !== null && } - {statusCash !== null && } - {statusInfluence !== null && } - {statusFavorability !== null && } {snapshot.inbox &&