Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
57cc6705f2 | ||
|
|
c9e9113a45 | ||
|
|
5e7ec903d3 | ||
|
|
0b946b743c | ||
|
|
86d486fb69 | ||
|
|
b4b25551ff | ||
|
|
8a12f07703 | ||
|
|
a84bc7ed21 | ||
|
|
7524f943d2 | ||
|
|
4f182a22b6 | ||
|
|
34b38dd5d5 | ||
|
|
b2133fd25c | ||
|
|
179fad450d | ||
|
|
85b7b07f53 | ||
|
|
5ef661a06f | ||
|
|
408cd933f4 | ||
|
|
3395fb4f90 | ||
|
|
537c494daa | ||
|
|
69b708dad3 | ||
|
|
e109e003c0 | ||
|
|
cbe0cda15d | ||
|
|
4620707abc | ||
|
|
3024606ac8 | ||
|
|
f44e7aa0f5 | ||
|
|
58d05f5287 | ||
|
|
e18d39edd0 | ||
|
|
a7150a1062 | ||
|
|
8eeef401ae | ||
|
|
f273d385c2 | ||
|
|
3b02c7feac | ||
|
|
1ba70ebbf3 | ||
|
|
08a819e44c | ||
|
|
50a9147665 | ||
|
|
5391636979 | ||
|
|
ab79d9b17f | ||
|
|
505a58b4fe | ||
|
|
2655ef81c8 | ||
|
|
ac4e3fa316 | ||
|
|
f2dbad5e03 | ||
|
|
096a6bfe61 | ||
|
|
71ee63b38a | ||
|
|
a4f7947666 | ||
|
|
570ad52d47 | ||
|
|
59974d1b79 | ||
|
|
af5176354a | ||
|
|
f5468bb640 | ||
|
|
0970ee4710 | ||
|
|
6e1439391a | ||
|
|
86379fc9c6 | ||
|
|
f0602453ea | ||
|
|
337eda2743 | ||
|
|
8852ae11f2 | ||
|
|
008a77e456 | ||
|
|
3e62d63418 | ||
|
|
09c1d8bcd8 | ||
|
|
0467b54c70 | ||
|
|
51d4f21d6b | ||
|
|
d8dc785757 | ||
|
|
eb69359a38 | ||
|
|
3acf471295 | ||
|
|
7d2f8f07c8 | ||
|
|
05d956f71b | ||
|
|
ae1cb93a4f | ||
|
|
687e4f2169 | ||
|
|
a801311fc5 | ||
|
|
1dc5beb0dd | ||
|
|
b6bfcedaf6 | ||
|
|
4c99dbe550 |
@@ -1 +1,2 @@
|
|||||||
# No environment variables required yet.
|
# No environment variables required yet.
|
||||||
|
GITEA_TOKEN=gitea-api-token
|
||||||
@@ -1,18 +1,16 @@
|
|||||||
# Flight Simulator — Workflow Rules
|
# Flight Simulator — Workflow Rules
|
||||||
|
|
||||||
## Change process (mandatory)
|
## Change process (mandatory)
|
||||||
1. **Small, incremental changes** — work is done one change at a time, in smaller parts; each part must be tested thoroughly with unit and e2e tests covering it before moving on.
|
1. **Small, incremental changes** — work is done one change at a time, in smaller parts; each part must be tested thoroughly with unit and e2e tests covering it before moving on. Connected issues/tasks that reference the same part of code MAY be done together on one branch/PR with a single version bump (e.g. two UI tweaks to the same panel).
|
||||||
2. **Feature branch + PR** — every change lands on a feature branch off `master` (no direct pushes to master). The branch carries the commits below; open a pull request to `master`.
|
2. **Feature branch + PR** — every change lands on a feature branch off `master` (no direct pushes to master). The branch carries the commits below; open a pull request to `master`.
|
||||||
3. **Changelog entry** — every such change is listed in `CHANGELOG.md` with date, time and version (format: `## v<version> — YYYY-MM-DD HH:MM`, then bullet points of what changed).
|
3. **Changelog entry** — every such change is listed in `CHANGELOG.md` with date, time and version (format: `## v<version> — YYYY-MM-DD HH:MM`, then bullet points of what changed).
|
||||||
4. **Version bump** — the version is updated in `package.json`.
|
4. **Version bump** — the version is updated in `package.json`.
|
||||||
5. **CI must pass** — the PR's pipeline (build → unit tests → e2e, `.gitea/workflows/ci.yml`) must be green before merging. CI never deploys to production; its e2e runs against an isolated stack inside dind.
|
5. **CI must pass** — enforced by branch protection on `master` (required status check `CI / build + unit + e2e (pull request)`): the PR cannot be merged until CI is green. Merge via auto-merge (`POST /repos/{owner}/{repo}/pulls/{n}/merge` with body `{"do":"merge","merge_style":"merge","merge_when_checks_succeed":true}`) so it merges automatically once CI passes. CI never deploys to production; its e2e runs against an isolated stack inside dind.
|
||||||
6. **Tag + manual deploy after merge** — once merged, tag the version on `master` (e.g. `v0.13.0`). Production (`https://flight.dev.kkhost.pl`) is updated manually afterwards: `docker compose up -d --build` on the host.
|
6. **Tag + manual deploy after merge** — once merged, tag the version on `master` (e.g. `v0.13.0`). Production (`https://flight.dev.kkhost.pl`) is updated manually afterwards: `docker compose up -d --build` on the host.
|
||||||
|
|
||||||
## E2E tests (mandatory)
|
## E2E tests (mandatory)
|
||||||
1. **Docker compose instance is the app under test** — e2e always runs against a docker-compose build, never a local `next dev` on :3000 (dev builds don't render for non-loopback clients, and a second instance splits state). Locally that means the Traefik-routed instance at `https://flight.dev.kkhost.pl`; in CI it is an isolated stack inside dind (`docker-compose.ci.yml`) — **CI never deploys to or modifies production**.
|
1. **CI-only** — e2e runs ONLY in CI, against an isolated docker stack inside dind built from `docker-compose.ci.yml` (project name `flight-ci`, app container on a static IP; see `.gitea/workflows/ci.yml`). There are NO local e2e runs at all: locally you verify with `tsc --noEmit` + `npx vitest run` + `npx playwright test --list` (typecheck, unit suite, specs compile and list), and the full e2e suite is verified by CI on every PR. **CI never deploys to or modifies production.**
|
||||||
2. **Update before testing (local)** — deploy current code first: `docker compose up -d --build`, then run the suite with plain `npx playwright test`. The config's webServer block is off by default; set `E2E_DEPLOY_CMD` to have Playwright itself run a deploy command and wait for readiness.
|
2. **CI env vars** (`playwright.config.ts`, all optional) — `E2E_BASE_URL` (app under test; CI sets it to the in-network app host, so the config's default of the live Traefik instance at `https://flight.dev.kkhost.pl` is never used), `E2E_DEPLOY_CMD` (runs as Playwright webServer: deploys the stack and waits for readiness before tests start; CI uses build + `up -d` + `logs -f`), `PW_REMOTE_BROWSER=0` (CI runs local chromium because the shared remote browser server at 192.168.1.4 cannot reach a stack inside dind — when unset, the config defaults to that remote server and to the live instance as baseURL), and `E2E_COMPOSE_ARGS`, read by `e2e/state.spec.ts` for its mid-run `docker compose restart flight` (CI points it at `-f docker-compose.ci.yml -p flight-ci`).
|
||||||
3. **Remote browsers** — local runs drive browsers through the shared Playwright server at `192.168.1.4:3000` (Docker image tag must match this repo's @playwright/test version, pinned in devDependencies). Set `PW_REMOTE_BROWSER=0` to run local chromium instead — CI does, because the remote server cannot reach a stack inside dind.
|
|
||||||
4. **CI env vars** (`playwright.config.ts`, all optional; defaults preserve the local flow) — `E2E_BASE_URL` (app under test), `E2E_DEPLOY_CMD` (webServer deploy command), `PW_REMOTE_BROWSER=0` (local browsers); `e2e/state.spec.ts` reads `E2E_COMPOSE_ARGS` for its mid-run container restart.
|
|
||||||
|
|
||||||
## API
|
## API
|
||||||
1. **Live base URL** — `https://flight.dev.kkhost.pl` (the docker-compose build behind Traefik).
|
1. **Live base URL** — `https://flight.dev.kkhost.pl` (the docker-compose build behind Traefik).
|
||||||
|
|||||||
+169
@@ -1,5 +1,174 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## v0.30.0 — 2026-09-20 19:47
|
||||||
|
- **Landing slows the sim to 1× instead of pausing; dispatch restores the last selected speed (ISS-057).** Replaces the v0.24.0 pause-on-landing behavior with a slow-down: in `tickOnce` (`lib/sim/engine.ts`), when ≥1 plane landed this tick and ANY plane is grounded ('available') afterwards, the sim drops to `MIN_TIME_SCALE` (1×) — a just-landed plane counts, so any real landing slows; a chained plane stays 'flying' via deliverPackages' auto-chain branch, so a pure-chain tick with nothing grounded does NOT slow. Pause becomes manual-only: ticks never set it anymore
|
||||||
|
- **Resume on dispatch.** `flyPlane` (`lib/game/actions.ts`) still clears a manually-paused sim on dispatch (kept), and now ALSO restores the last manually selected speed when this dispatch took the LAST grounded plane airborne — fresh-select 'available' planes after the update, and if zero remain set `timeScale = lastSelectedTimeScale`. With another plane still grounded the sim stays at 1×
|
||||||
|
- **New column `last_selected_time_scale` on `sim_state`** (`lib/db/schema.ts`, DDL + guarded `ALTER TABLE … DEFAULT 1` migration in `lib/db/client.ts`; pre-existing rows backfill to their OWN current `time_scale`, so a legacy DB resumes at the speed it was running). Written by `applyTimeControls` whenever a POST /api/sim body carries `timeScale` (clamped value); a `{paused}`-only post never touches it — last manual intent wins as the resume target with no extra flag. Seed sets it to 1 (`lib/game/seed.ts`)
|
||||||
|
- No snapshot/OpenAPI/route/client changes: the slider and speed label re-read `timeScale` from each poll automatically, so the slow-down and the resume are visible in the UI without any client work
|
||||||
|
- Tests: unit — `lib/sim/engine.test.ts` pause-on-landing describe rewritten for the slow/resume semantics (last landing at 1000× → paused=false + timeScale=1 + lastSelectedTimeScale preserved; landing with another plane still flying → slows, literal issue reading; already at 1× stays; chained-plane tick does NOT slow; manually-paused sim untouched by ticks), `lib/game/actions.test.ts` dispatch test rewritten (sole grounded plane → resumes to lastSelectedTimeScale=250 + unpauses; second grounded plane → stays 1×), new `app/api/sim/route.test.ts` case (POST {timeScale} records the row's lastSelectedTimeScale, POST {paused}-only leaves it untouched — read via getGameDb()), `lib/game/seed.test.ts` exact-equality gains the field, `lib/db/client.test.ts` legacy-migration fixture bumps time_scale to 50 and asserts the backfill. E2E — `e2e/pause-on-landing.spec.ts` renamed to `e2e/slow-on-landing.spec.ts` and rewritten: after landing assert `paused === false && timeScale === 1`; the /fly post-action snapshot asserts `timeScale === 1000` via resume (setScale posts 1000, so lastSelected=1000). Other specs' setScale helpers post {timeScale, paused:false} and keep working unchanged
|
||||||
|
- Verified: `tsc --noEmit` clean; unit suite green locally (327, was 325 — +2 new cases; engine describe rewritten in place); `npx playwright test --list` = 46 tests in 13 files (unchanged — the spec rename keeps the count); e2e not run locally by design — CI verifies against an isolated stack
|
||||||
|
|
||||||
|
## v0.29.1 — 2026-09-20 18:22
|
||||||
|
- Removed the flaky 'time controls' e2e test from `e2e/panes.spec.ts` (keyboard-driven slider assertions timed out randomly in CI); pause semantics remain covered by `e2e/sim.spec.ts` and `e2e/pause-on-landing.spec.ts`.
|
||||||
|
|
||||||
|
## v0.29.0 — 2026-09-20 14:27
|
||||||
|
- **Ignore a job (ISS-047, part B).** A player can now dismiss an open job so it leaves the market permanently; new random jobs spawn in its place via the existing top-up logic (`spawnOpenPackages` counts 'open', so the market refills to 10 on the next tick). New terminal package status `'ignored'` added to the status union/enum in `lib/db/schema.ts`, `lib/game/state.ts`, `lib/openapi.ts` (PackageState.status) and the e2e-local interface copy in `e2e/right-pane.spec.ts`. No DB migration — the column is plain TEXT with no CHECK constraint. New action `ignorePackage` (`lib/game/actions.ts`) next to abandon: 404 unknown id, 409 unless open ("only open packages can be ignored"), otherwise flips status to 'ignored' — no body, no penalty, nothing else changes
|
||||||
|
- **New route.** `POST /api/packages/{id}/ignore` (`app/api/packages/[id]/ignore/route.ts`) — no body, mirrors the abandon route exactly (same performAction wrapper, full state snapshot on success). The 13th public endpoint: OpenAPI spec gains the path + 'ignored' in PackageState.status; `lib/openapi.test.ts` and `e2e/api.spec.ts` path lists updated twelve → thirteen
|
||||||
|
- **UI.** Each open-package row in the Jobs tab gains a small "Ignore" button beside the Load controls (`components/RightPane.tsx`, testid `ignore-{pkg.id}`, disabled while the pane action is busy, calls runAction with no body). Ignored rows vanish from the list automatically — the section filters status==='open'; no toast (deriveEvents untouched)
|
||||||
|
- Verified-safe consumers unchanged: expirePackages selects only open|loaded ('ignored' never expires), deliverPackages handles loaded/expired, RightPane filters 'open'
|
||||||
|
- Tests: unit — new `ignorePackage` block in `lib/game/actions.test.ts` (open → ignored with cash/planeId untouched; 409 for each of loaded/delivered/expired/abandoned/already-ignored; 404 unknown id), `lib/sim/engine.test.ts` terminal-statuses test gains an 'ignored' row, `lib/openapi.test.ts` status enum list gains 'ignored'. E2E — new "Ignore removes an open job from the list permanently" test in `e2e/right-pane.spec.ts`: hook-created package renders with an enabled Ignore button, UI click → /api/state shows 'ignored', row gone from `[data-testid="open-packages"]`, second API ignore 409s
|
||||||
|
- Verified: `tsc --noEmit` clean; unit suite green locally (325, was 318); `npx playwright test --list` = 47 tests in 13 files (was 46/13 — the new ignore test); e2e not run locally by design — CI verifies against an isolated stack
|
||||||
|
|
||||||
|
## v0.28.0 — 2026-09-20 13:55
|
||||||
|
- **Right pane reworked into tabs (ISS-047, part A).** The right pane now has a tab bar under the "Jobs & Market" heading with two tabs — `tab-jobs` ("Jobs", default-active) and `tab-planes-market` ("Planes market") (`components/RightPane.tsx`, new `.pane-tabs`/`.tab-btn` CSS in `app/globals.css`). The Jobs tab is the existing Packages section moved verbatim (content, testids and hover behavior unchanged); the Planes market tab holds the existing buy/sell rows (testids unchanged) plus a tech-spec panel per catalog type — one card (`plane-type-{model}`) with price, sell value (price × SELL_FRACTION), max payload in tonnes, cruise speed, fuel burn, max fuel and **max range**, ordered by price ascending. The inactive tab unmounts; the `cargoWeightFor`/`loadEligiblePlanes` exports are untouched
|
||||||
|
- **Five new plane types — progression ladder above the ATR starter (ISS-047).** CRJ-900 (€450k), Embraer E175 (€900k), Airbus A320-200 (€1.8M), Airbus A330-200 (€4.5M) and Boeing 777-300ER (€9M) added to `PLANE_TYPES` in `lib/game/catalog.ts` with the exact balance values from the issue (bigger tanks, faster airframes, more payload). Purely additive — everything downstream (buy validation, movement math, load validation, snapshot catalog) is data-driven via `PLANE_TYPES[model]`, so no endpoint or schema change; the OpenAPI spec and its e2e path list stay at twelve
|
||||||
|
- **Derived max range (ISS-047).** New pure `maxRangeKm(burnPerKm, emptyWeightKg, maxFuel)` in `lib/sim/movement.ts` — closed form of the weighted burn model solving `requiredFuelFor(d) = maxFuel`: `ln(1 + ρF/We)·(We + ρF)/(ρ·burnPerKm)` (reuses `FUEL_DENSITY_KG_PER_L`, guards We > 0, zero fuel → 0). ATR 72-600 full tank ≈ 4436 km. Display-only — the sim still does not model range exhaustion
|
||||||
|
- **Sell-plane cargo guard (ISS-047).** `sellPlane` (`lib/game/actions.ts`) now 409s with "cannot sell a plane carrying cargo" when the grounded plane has any `loaded`/`expired` packages bound to it — previously selling such a plane orphaned its cargo (packages stuck 'loaded' with a dangling planeId that could never deliver). Same query pattern as `loadPackage`; the last-plane and flying-plane guards are unchanged
|
||||||
|
- Tests: unit — new `lib/sim/movement.test.ts` block for `maxRangeKm` (ATR ≈ 4439 km ±5%, monotonic in tank size, inverse in burn rate, zero fuel → 0, We ≤ 0 throws), new `lib/game/catalog.test.ts` sanity file (positive specs + unique ids across all six types, atr72 is STARTER_MODEL), `lib/game/actions.test.ts` sellPlane gains a loaded-cargo 409 case (row left untouched). E2E — `e2e/right-pane.spec.ts`: the market test clicks `tab-planes-market` first and a new "Planes market tab lists all plane types with tech specs" test asserts six catalog entries via /api/state, the ATR card's name + range against an in-test mirror of `maxRangeKm`, and the Boeing 777 card with its €9M price; `e2e/toasts.spec.ts` clicks the tab before its market-buy flow; `e2e/panes.spec.ts` asserts both tab buttons render with Jobs default-active. No new endpoints — `lib/openapi.test.ts` untouched
|
||||||
|
- Verified: `tsc --noEmit` clean; unit suite green locally (318, was 311); `npx playwright test --list` = 46 tests in 13 files (was 45/13 — the new spec-panel test); e2e not run locally by design — CI verifies against an isolated stack
|
||||||
|
|
||||||
|
## v0.27.1 — 2026-09-20 13:16
|
||||||
|
- Right pane widened from 280px to 360px to match the left pane; toast stack offset adjusted to stay flush with the map's right edge (ISS-046).
|
||||||
|
|
||||||
|
## v0.27.0 — 2026-09-20 12:27
|
||||||
|
- **Packages now have real weight (ISS-045).** New `weight_kg REAL NOT NULL DEFAULT 2000` column on `packages` (`lib/db/schema.ts`, DDL + guarded `ALTER TABLE` migration in `lib/db/client.ts`; pre-existing rows backfill to the mid-range default). `generatePackage` draws it AFTER cargoCount: `UNIT_WEIGHT_KG[cargoType] × cargoCount × (0.7 + 0.6·rng())`, rounded to integer kg — one extra RNG draw per package, so the documented fixed draw order is now origin, dest, cargoType, cargoCount, weight jitter, [deadline window]. New tunable table `UNIT_WEIGHT_KG` in `lib/game/seed.ts` (Passengers 50 / Mail 60 / Perishables 70 / Electronics 40 / Auto parts 72 kg per passenger/pallet), chosen so every cargo type at MAX count × max jitter (1.3×) still fits the ATR alone and typical packages land ~400–2500 kg
|
||||||
|
- **Plane capacity is now max payload kg, not 6 slots (ISS-045).** `capacity` REMOVED from `PlaneType`/`CatalogEntry`/snapshot catalog; replaced by `maxPayloadKg` — ATR 72-600 = 4800 kg (`lib/game/catalog.ts`). Server load validation (`loadPackage`, `lib/game/actions.ts`) now sums `weightKg` over the plane's loaded+expired packages and 409s with `no payload room: the ATR 72-600 carries X/Y kg` when the new package doesn't fit; expired cargo still occupies its payload. Client mirrors it: `slotsUsedFor` → `cargoWeightFor(state, planeId)` (summed kg) in `components/RightPane.tsx`, and `loadEligiblePlanes` compares used + package weight ≤ catalog maxPayloadKg so the Load button state always matches what the server accepts
|
||||||
|
- **Payout now includes a per-kg part (ISS-045).** New `rewardFor(km, weightKg) = round(BASE_REWARD + REWARD_PER_KM·km + REWARD_PER_KG·weightKg)` with `REWARD_PER_KG = 0.5` (`lib/game/seed.ts`) — replaces the distance-only `rewardForDistanceKm`, which is deleted (no remaining callers). Typical hops stay in the ~€1–3k band
|
||||||
|
- **Loadout display shows tonnage (ISS-045).** Left-pane fleet rows now render `X.Xt / Y.Yt` (used/max payload, one decimal) instead of `n/6 pkgs`; the on-board block filter switches to weight-based. No new endpoints — OpenAPI only gains `PackageState.weightKg` and swaps `CatalogEntry.capacity` → `maxPayloadKg`, so the e2e path list stays at twelve
|
||||||
|
- **Test hook gains a forced weight (ISS-045).** `generatePackage` accepts an optional `weightKg` that skips the jitter RNG draw (same pattern as the v0.8.0 forced endpoints), and `POST /api/test/create-package` passes it through — so e2e flows that load several packages onto one plane stay under its payload deterministically instead of flaking on two heavy random draws (~13% would otherwise exceed 4800 kg). The hook is test-only (FLIGHT_TEST_HOOKS=1) and not part of the documented API, so the OpenAPI path list stays at twelve
|
||||||
|
- Tests: unit — `lib/game/seed.test.ts` (reward expectations → new formula incl. per-kg part; new balance-constraint test asserting every seeded package is a positive integer kg ≤ starter maxPayloadKg; forced-weight block), `lib/game/actions.test.ts` (loadPackage fill loop now inserts weights summing past maxPayloadKg → `/no payload room/`; expired-still-occupies reworked weight-based), `components/right-pane.test.ts` (`cargoWeightFor` sums + partial-payload eligibility case; CATALOG fixture drops capacity, gains maxPayloadKg), `lib/openapi.test.ts` (exact key lists for PackageState + CatalogEntry). Type-compat only: catalog fixtures in `deriveEvents`/`mapData` tests and the e2e interfaces. E2E — `e2e/right-pane.spec.ts` asserts `maxPayloadKg === 4800`; `e2e/panes.spec.ts` loadout regex → `/^\d+\.\dt \/ \d+\.\dt$/`; snapshot key lists in `app/api/state/route.test.ts` + `e2e/state.spec.ts` gain `weightKg`; the two multi-load tests in `e2e/actions.spec.ts` pass forced weights. Fuel math untouched — the refuel-forFlight exact-liter mirrors stay as-is
|
||||||
|
- Verified: `tsc --noEmit` clean; unit suite green locally (311, was 308); `npx playwright test --list` = 45 tests in 13 files (unchanged); e2e not run locally by design — CI verifies against an isolated stack
|
||||||
|
|
||||||
|
## v0.26.0 — 2026-09-20 11:28
|
||||||
|
- **Flight queue UI + map rendering (ISS-043, part 2).** Builds on the part-1 backend (`PlaneState.queue`, `POST /api/planes/{id}/queue` + `/queue/cancel`, auto-chain on landing) — no new endpoints, so the OpenAPI spec and its e2e path list are untouched
|
||||||
|
- **Dotted queue line on the map (ISS-043).** New pure builder `queuedRoutesGeoJson(planes, airportsByIcao)` in `lib/mapData.ts`: one LineString per FLYING plane with a non-empty queue, chaining `dest → queue[0] → …` — ONLY the not-yet-started legs (the active leg stays in the solid `routes-legs` layer). Reuses `greatCircleArc`, same feature/properties shape as `routesGeoJson` (`{planeId}`); arcs concatenated with the shared joint point dropped once; a plane is skipped, never guessed, when its dest or any queued ICAO is missing from the airport index. New GeoJSON source + line layer in `components/Map.tsx` — id `queue-routes`, muted slate `#64748b`, width 3, dotted via `'line-dasharray': [0.1, 1.5]` (distinct from the solid amber active leg and the `[2,2]` yellow hover dash), added after `routes-legs` but before the hover layers so a hovered trace still draws on top; pushed each poll in `applyDynamicRef` alongside the solid legs
|
||||||
|
- **Queue sub-section in the left pane's On board block (ISS-043).** Each on-board plane block now carries a "Queue" sub-section after its cargo rows: one row per queued leg (`queue-leg-{i}`) showing destination name + ICAO with a Cancel button (`queue-cancel-{i}` → `POST …/queue/cancel {index:i}`), plus an add control — airport `<select>` (`queue-add-dest`) + "Add to queue" button (`queue-add` → `POST …/queue {destIcao}`) reusing the pane's already-fetched `airportOptions` (no second `/api/airports` fetch); buttons disable on `actionsBusy`, add also disables until an airport is picked. The on-board block filter now ALSO includes planes with a non-empty queue, so a queued plane always shows its block even when grounded with nothing on board. Existing cargo-row testids/behavior (`onboard-package-*`, `fly-to-*`, `refuel-for-*`, `abandon-*`) unchanged
|
||||||
|
- Tests: unit — `lib/mapData.test.ts` gains a `queuedRoutesGeoJson` block mirroring the `routesGeoJson` tests (grounded plane with queue → nothing; flying with empty queue → nothing; flying with a 2-leg queue → one feature starting at DEST, passing through each queued airport exactly at the arc joints, ending at the last queued ICAO, length `n_legs × SEGMENTS + 1`; missing dest or queued ICAO → skipped; multiple planes → only qualifying ones draw). E2E — new `e2e/queue.spec.ts` (serial): (1) queue display + cancel through the real UI — load a package at EDDF, start leg 1 via the fly-to button, freeze mid-flight, add a leg via `queue-add-dest`/`queue-add`, assert `queue-leg-0` appears with its destination, cancel it and assert it's gone; (2) dotted map line — flying plane with one queued leg: fit to both endpoints and assert some rendered `queue-routes` segment starts within EPS of DEST and some ends within EPS of the queued airport ACROSS per-tile segments (plain-object mapping in-page per ORCHESTRATOR §6), no segment starts at the hub (the active leg is NOT in this layer) and every feature carries `planeId: plane-starter`; (3) auto-chain end-to-end — full tank, package EDDF→LEMD + queued return LEMD→EDDF, start leg 1, fast-forward at 1000× and assert the server AUTO-STARTS the chained leg (`status 'flying'` to EDDF with no manual dispatch) with the package already delivered (part-1 ordering: delivery before chaining); all three leave the starter grounded at EDDF for later specs
|
||||||
|
- Verified: `tsc --noEmit` clean; unit suite green locally (308, was 303); `npx playwright test --list` = 45 tests in 13 files (was 42/12 — the new queue spec); e2e not run locally by design — CI verifies against an isolated stack
|
||||||
|
|
||||||
|
## v0.25.0 — 2026-09-20 10:36
|
||||||
|
- **Planes now hold a queue of upcoming flight legs (ISS-043, part 1 — backend).** One new column on `planes`: `queue TEXT NOT NULL DEFAULT '[]'` (`lib/db/schema.ts`, DDL + guarded `ALTER TABLE` migration in `lib/db/client.ts`) storing an ordered JSON array of ICAO strings = the legs NOT yet started. The active leg stays exactly as before (`destIcao` + `departureSimTime`); full path = `[locationIcao, destIcao, ...queue]`. No new table — queues are short, per-plane, always read/written whole
|
||||||
|
- **Auto-chain on landing (ISS-043).** In `deliverPackages()` (`lib/sim/engine.ts`) a plane that arrives now reads its queue: if it holds legs AND fuel covers the first one (same `requiredFuelFor` feasibility rule as `/fly`), it immediately starts that leg from the arrival airport — stays `'flying'`, `departureSimTime` = the arrival instant, queue shortened. If fuel is short it grounds safely with the remaining queue kept intact for refuel + re-dispatch; an empty queue grounds exactly as before. Cargo delivery for the reached airport runs first and is unaffected by chaining. Ordering preserved on purpose: delivery runs BEFORE tickOnce's pause check (ISS-041), so a chained plane counts as still flying there — chaining never triggers the last-plane pause
|
||||||
|
- **New endpoints (ISS-043).** `POST /api/planes/{planeId}/queue` body `{destIcao}` appends a not-yet-started leg (works grounded or flying — pre-build a route; nothing auto-starts, 400 unknown ICAO/bad body, 404 unknown plane); `POST /api/planes/{planeId}/queue/cancel` body `{index}` removes a queued leg by index (only queued legs are cancellable — the active in-flight leg is never touched; 400 non-integer/out-of-range index, 404 unknown plane). Both run through `performAction()` like every other action and return the full state snapshot. New actions `queueLeg`/`cancelQueuedLeg` in `lib/game/actions.ts`; routes under `app/api/planes/[planeId]/queue/`
|
||||||
|
- **Snapshot + spec (ISS-043).** `PlaneState.queue: string[]` added to the `/api/state` snapshot (`lib/game/state.ts`, parsed with a null/malformed-safe helper shared by the engine); OpenAPI updated — `PlaneState.queue`, `QueueLegRequest`, `CancelQueuedLegRequest`, both new paths (200→snapshot, 400, 404)
|
||||||
|
- Tests: unit — `lib/sim/engine.test.ts`: auto-chain block in `deliverPackages` (lands with queue + enough fuel → `'flying'` to the next dest at the arrival instant with the queue shortened; lands short on fuel → grounds with the queue intact; empty queue → unchanged grounding) plus a pause-on-landing regression guard — a chained plane does NOT trigger the last-plane pause. `lib/game/actions.test.ts`: `queueLeg` (appends in order, works while flying without touching the active leg, 404 unknown plane, 400 unknown ICAO) and `cancelQueuedLeg` (removes the right index keeping order, 400 out-of-range/negative/empty-queue, 404 unknown plane). `lib/openapi.test.ts`: endpoint count ten → twelve, PlaneState keys + both request schemas. Type-compat only: `queue: []` added to the `PlaneState`/seed fixtures in `deriveEvents`, `right-pane`, `mapData`, `seed` tests
|
||||||
|
- Part 1 of ISS-043 (backend) — UI/map rendering of queued legs lands in a follow-up part. Verified: `tsc --noEmit` clean; unit suite green locally; `npx playwright test --list` unchanged at 42 tests in 12 files; e2e not run locally by design — CI verifies against an isolated stack
|
||||||
|
|
||||||
|
## v0.24.0 — 2026-09-20 09:48
|
||||||
|
- **Landing now pauses the sim instead of auto-slowing to 1× (ISS-041).** When the LAST plane in flight lands, `tickOnce` (`lib/sim/engine.ts`) sets `sim_state.paused = true` WITHOUT touching `timeScale` — speed is preserved. The trigger condition carries over from ISS-011's auto-slow unchanged: ≥1 landing this tick AND no `'flying'` planes remain (a landing while another plane is still airborne does not pause — there would be nothing to auto-resume it). No idle-enforcement or auto-restore of the pause exists
|
||||||
|
- **Starting a flight auto-resumes a paused sim (ISS-041).** `flyPlane()` (`lib/game/actions.ts`) writes `sim_state.paused = false` before persisting — inside `runAction()`, so tick + unpause + dispatch are atomic under the sim lock. The cycle: dispatch unpauses → last landing pauses (speed preserved) → next dispatch unpauses again
|
||||||
|
- Tests: unit — `lib/sim/engine.test.ts`: the auto-slow describe block rewritten for pause semantics (last plane lands → `paused === true` AND stored `timeScale` UNCHANGED, persisted on the DB row; a landing while another plane is still flying → no pause; last landing at scale 1 → pauses anyway; paused tick with a fully grounded fleet → trigger never fires). `lib/game/actions.test.ts`: new test — dispatching on a paused sim clears `paused` and leaves `timeScale` untouched. E2E — `e2e/auto-slow.spec.ts` renamed to `e2e/pause-on-landing.spec.ts` and reworked: after the starter lands, asserts `simState.paused === true` AND `timeScale` still 1000 (NOT reset), then a subsequent `/fly` dispatch clears `paused` on its own post-action snapshot. Cross-cutting fix for the new pause: every per-spec `setScale` helper (`actions`, `hover`, `map-interactions`, `relocation`, `right-pane`) now POSTs `{ timeScale, paused: false }` — a landing pauses the sim, so a scale-only fast-forward after one would leave the clock frozen and hang the next wait; no caller relied on it NOT clearing pause (verified per call site). Deliberate mid-test pauses (`sim.spec.ts` / `panes.spec.ts` freeze tests, marker-click freezes) are untouched
|
||||||
|
- Verified: `tsc --noEmit` clean; unit suite green locally (291); `npx playwright test --list` = 42 tests in 12 files; e2e not run locally by design — CI verifies against an isolated stack
|
||||||
|
|
||||||
|
## v0.23.2 — 2026-09-20 09:15
|
||||||
|
- **On-board package hover previews the route from the carrier's current position (ISS-040).** Hovering a loaded package in the left pane used to draw the great-circle trace from the package's ORIGIN airport; it now starts at the carrying plane's live lat/lon — identical while grounded at the pickup, correct once the plane has departed with cargo still loaded. New pure builder `hoverTraceGeoJson(from: AirportCoord, toIcao, airportsByIcao)` in `lib/mapData.ts` (sibling of `hoverRouteGeoJson`, same shape/conventions; empty collection when the destination is missing); `components/Map.tsx`'s `applyHoverRef` looks up the carrier via the hover's `planeId` and uses it, falling back to the ICAO trace when no carrier is in state. The `[state]` effect now also re-applies the hover so the trace follows a moving carrier between polls while hovered (idempotent: one small setData + ring filters). Endpoint rings untouched — still ICAO-filtered origin/dest circles
|
||||||
|
- Tests: unit — `lib/mapData.test.ts` gains a `hoverTraceGeoJson` block (exact endpoints from an arbitrary start coord; empty on missing dest). E2E — `e2e/hover.spec.ts`: new test loads a package at EDDF, dispatches the starter to LEMD via API, waits until its live position is >0.2° away from the hub, pauses the sim, hovers the on-board row and asserts some rendered trace segment starts within EPS of the carrier's live lat/lon AND some ends within EPS of LEMD AND no segment starts near EDDF (per-tile clipping handled via the existing cross-segment endpoint pattern); cleanup resumes + fast-forwards to arrival (auto-delivery) and flies home
|
||||||
|
|
||||||
|
## v0.23.1 — 2026-09-20 08:42
|
||||||
|
- **Toasts repositioned to the map's right edge (ISS-039).** The `.toasts` stack was `position: fixed` at the viewport bottom-right, overlapping the 280px right pane; its `right` changed 12px → 292px (= 280px right pane + 12px inset) so it now sits flush against the map's right edge with the same 12px margin. No JSX/endpoint changes — all positioning lives in that one CSS value
|
||||||
|
- Tests: e2e wording only — `toasts.spec.ts` header comment, test title, and toast visibility assertion message updated from "bottom-right" to "map right edge / clear of the right pane"; no position assertions added (none existed), suite unchanged at 41 tests in 12 files
|
||||||
|
- Verified: `tsc --noEmit` clean; unit suite green locally (288); `npx playwright test --list` = 41 tests in 12 files; e2e not run locally by design — CI verifies against an isolated stack
|
||||||
|
|
||||||
|
## v0.23.0 — 2026-09-20 08:25
|
||||||
|
- **Refuel-to-full row moves to the left pane (ISS-035).** Refueling a grounded plane is "anything with our plane", so it belongs in the left pane next to Relocate, not as a market row on the right. The `.market-row` JSX (`market-refuel-none` "All tanks full." span / `market-refuel-plane` select of grounded planes labeled `{planeName} — {fuel}/{maxFuel} L`, `market-refuel-cost` preview, `market-refuel` button → `POST /api/planes/{id}/refuel`) moved verbatim from the Market section in `components/RightPane.tsx` into a new "Refuel" `<section data-testid="refuel-section">` in `components/LeftPane.tsx`, inserted between Relocate and Time. Its state (`refuelPlaneId`) + derived values (`refuelable`, effective-selection `refuelPlane`, `refuelCost`) moved with it, reusing LeftPane's existing `grounded` list; busy gating rewired from RightPane's `busy` to LeftPane's own `useGameAction` instance (`actionsBusy`). Testids kept byte-identical so all e2e locators are unchanged. The per-package "Refuel" button in the On board section (`refuel-for-{pkg.id}`, mode 'forFlight') is a different feature and stays put; exported helpers `slotsUsedFor` / `loadEligiblePlanes` untouched
|
||||||
|
- Tests: e2e — `right-pane.spec.ts`: the market test keeps its buy/sell assertions, renamed to reflect that the refuel row now renders inside `[data-testid="left-pane"]` (asserted before the click); functional cash/tank assertions unchanged; the for-leg test's title/comment updated from "market button" to left pane. `panes.spec.ts`: first test gains structural assertions — Refuel heading + `market-refuel` visible in the left pane, both absent from the right pane (same present-in-left / absent-from-right pattern as On board). No unit-test changes (suite stays at 288)
|
||||||
|
- Verified: `tsc --noEmit` clean; unit suite green locally (288); `npx playwright test --list` = 41 tests in 12 files; e2e not run locally by design — CI verifies against an isolated stack
|
||||||
|
|
||||||
|
## v0.22.2 — 2026-09-20 07:32
|
||||||
|
- Docs: ORCHESTRATOR.md successor-agent manual committed to the repo; its token reference now points to the gitignored local .env (GITEA_TOKEN, rotated after the Sept 2026 incident); §9 rewritten as durable 'how to find current state' guidance instead of a stale snapshot; no code changes
|
||||||
|
|
||||||
|
## v0.22.1 — 2026-09-20 06:57
|
||||||
|
- Hygiene: gitignore the local-only ORCHESTRATOR.md successor-agent manual (it references host-specific setup and must never be version-controlled); no code changes
|
||||||
|
|
||||||
|
## v0.22.0 — 2026-09-19 21:42
|
||||||
|
- **Hover route trace on job-list rows (ISS-022).** Hovering an open package in the right pane now draws the ENTIRE great-circle trace between origin and destination, not just the two endpoint rings. Zero pane edits — the rows already sent `{kind:'package', originIcao, destIcao}`; `components/Map.tsx` now derives from/to for any hover target carrying two ICAOs and pushes a new pure builder's output (`hoverRouteGeoJson(fromIcao, toIcao, airportsByIcao)` in `lib/mapData.ts`: one LineString via the existing `greatCircleArc` slerp, empty FeatureCollection when either endpoint is missing from the airport index or the `''` no-hover sentinel) into a NEW dedicated `hover-routes` GeoJSON source + top-most dashed `hover-route` LineLayer (paint: `#facc15` matching the airports-highlight ring, width 4, `line-dasharray [2,2]`). The shared `routes` source can't carry this — it only holds FLYING legs, so an open package's or a grounded relocation's planned route was never in it. The layer is added in `ensureLayers` after the highlight layers so style switches keep it; `applyHoverRef` re-pushes data on every hover
|
||||||
|
- **Same trace on On-board cargo rows (ISS-025).** Each `onboard-package-{id}` row in the left pane's On board section now reports `{kind:'package', originIcao, destIcao, planeId: plane.id}` on mouseenter — same full trace as job-list rows PLUS the carrying plane's halo stays lit via the new optional `planeId` field (Map uses `h.planeId ?? ''` for the planes/routes-highlight filters). Mouseleave restores the block's plain `{kind:'plane', id}` highlight; leaving the whole block still ends at null because React fires the child's mouseleave before the parent's
|
||||||
|
- **Relocate panel hover previews the planned flight (ISS-027).** The left pane's Relocate section gains `data-testid="relocate-section"` + enter/leave handlers: with a grounded plane AND destination selected it reports `{kind:'route', fromIcao: relocatePlane.locationIcao, toIcao: relocateDest.icao}` (else null), and Map draws the planned trace AND rings ONLY the target airport in airports-highlight (origin stays unmarked — the destination is what the issue asks to see). `HoverTarget` (`components/hoverTypes.ts`) extends to `{kind:'plane';id} | {kind:'package';originIcao;destIcao;planeId?} | {kind:'route';fromIcao;toIcao}`. Existing semantics unchanged: plane hovers filter the three highlight layers exactly as before, package hovers keep BOTH endpoint rings (now plus the trace)
|
||||||
|
- **Target airport highlighted in a distinct color on job-list / relocation hover (ISS-022).** The destination of any two-endpoint hover now gets its own ring in a NEW top-most `airports-target-highlight` circle layer (`components/Map.tsx`, same `airports` source and r=9 transparent-fill geometry as airports-highlight, but green `#4ade80` stroke width 3 vs the yellow `#facc15` endpoint rings) — added last in `ensureLayers` so it also sits above the hover-route line at its endpoint; `applyHoverRef` filters it to the destination icao for BOTH `'package'` and `'route'` hovers (empty-string sentinel otherwise). airports-highlight itself is untouched, so the existing both-endpoints / target-only assertions stay valid
|
||||||
|
- Tests: unit — new `describe('hoverRouteGeoJson …')` in `lib/mapData.test.ts`: no-hover sentinel → empty; two known airports → one arc with exact dataset endpoints; reversed-input symmetry; missing from/to ICAO → empty (baseline 283 → 288). e2e (`e2e/hover.spec.ts`) — open-package test extended with hover-route endpoint assertions (line geometry first/last coords compared against `/api/airports` lookups) + trace-clear check; new `hovering an on-board cargo row draws its trace and keeps the plane halo` (load via API, hover the row, assert trace endpoints + planes-highlight for that plane, abandon the package afterwards to leave a clean instance); new `hovering the Relocate section previews the planned route and target airport` (selects starter + LEMD via the existing testids, hovers `[data-testid="relocate-section"]`, asserts trace endpoints + target-only ring). New helpers: `airportLonLat(page, icao)` and `expectHoverRoute(page, fromIcao, toIcao)`; all new/extended assertions call `fitToAirports` first since `queryRenderedFeatures` is viewport-scoped
|
||||||
|
- Verified: `tsc --noEmit` clean; unit suite green locally (288); `npx playwright test --list` = 41 tests (was 39, +2 new in hover.spec.ts); e2e not run locally by design — CI verifies against an isolated stack
|
||||||
|
- **Fix: hover-route e2e timeouts (CI run #69).** All three trace tests failed at `expectHoverRoute` with the 15 s "waiting for the hover-route line EDDF → LEMD" timeout although the dashed trace WAS drawn correctly — the helper assumed `queryRenderedFeatures(undefined, {layers:['hover-route']})` returns exactly one feature whose endpoints are bit-identical to the `/api/airports` dataset coords. MapLibre GL JS stores GeoJSON geometry in per-tile INTEGER grids (`Math.round(extent·(x·2^z − tx))`, maplibre-gl 6.10) and clips long lines across tiles, so a 1420 km leg comes back as one feature PER intersecting tile (empirically 4 at z=4 / 5 at z=5 for EDDF→LEMD, verified against the installed build's GeoJSONVT) with endpoints quantized by up to ~half a grid step (~0.001° observed at z≥4, ~0.02° worst case at z=0): both the `feats.length !== 1` guard and the strict `===` coordinate comparisons could never be true. The helper now accepts any number of segments and matches endpoints within 0.05° (~5 km — above worst-case quantization at any zoom, below the distance between any two EU airports): some segment must start at origin and some end at destination; all other assertions unchanged. App side verified correct (no race: `ensureLayers` awaits the airport fetch before creating sources/layers and re-applies hover afterwards; layer/source ids match) — no app changes
|
||||||
|
- **Fix: hover-route e2e — evaluate maplibre geometry in-page before Playwright serialization (CI runs #69–#71).** All three trace tests failed for a serialization reason, not a data one: `renderedFeatures` returned live `GeoJSONFeature` instances from `queryRenderedFeatures`, whose `geometry` is a lazy PROTOTYPE getter — and Playwright's evaluate serialization copies only own enumerable properties (verified empirically), so every feature arrived in test context WITHOUT geometry. Run #69 timed out on the strict length guard before touching it, run #70 threw `TypeError: Cannot read properties of undefined (reading 'coordinates')`, run #71's defensive filter found nothing and timed out. The helper now maps each feature to a plain object inside page.evaluate so the getter is evaluated in-page; the endpoint-matching predicate keeps its degenerate-segment filter as belt-and-braces — no app changes
|
||||||
|
|
||||||
|
## v0.21.0 — 2026-09-19 21:01
|
||||||
|
- **Relocate panel moves to the left pane (ISS-023).** Flying an empty/grounded plane to another airport is "anything with our plane", so it belongs in the left pane, not as a market row on the right. The `.market-row.market-row-relocate` JSX (`relocate-plane` select of grounded planes labeled `{planeName} — {icao}`, `relocate-dest` name-sorted select, `relocate-go` button → `POST /api/planes/{id}/fly {destIcao}`) moved verbatim from `components/RightPane.tsx` into a new "Relocate" `<section>` in `components/LeftPane.tsx`, inserted between On board and Time. Its state (`relocatePlaneId` / `relocateDestIcao`) and the one-time `/api/airports` fetch (promise-ref pattern, GeoJSON → `{name, icao}[]` sorted by name) moved with it — the relocate-dest select was that fetch's only consumer in RightPane, so nothing else there changed. Busy gating rewired from RightPane's `busy` to LeftPane's own `useGameAction` instance (`actionsBusy`); a grounded-plane filter was added next to the existing `onboard` compute; plane labels reuse the expression already inlined in the Fleet rows. Testids kept byte-identical (`relocate-plane` / `relocate-dest` / `relocate-go`) and the row keeps its `.market-row market-row-relocate` classes (global CSS, works in the 360 px left pane); stale "280 px right pane" comment updated in `app/globals.css`. The map-popup relocation controls (`airport-popup-*`, Map.tsx) are a separate surface fed by the snapshot only — untouched
|
||||||
|
- Tests: e2e — only `relocation.spec.ts` touches these testids and all locators are global, so no locator changes; the first test's title (which mentioned "right pane") and the file header comments now say left-pane Relocate section. No unit-test changes (baseline 283)
|
||||||
|
- Verified: `tsc --noEmit` clean; unit suite green locally; e2e not run locally by design — CI verifies against an isolated stack
|
||||||
|
|
||||||
|
## v0.20.0 — 2026-09-19 19:21
|
||||||
|
- **On board moved to the left pane (ISS-021).** The "On board" section (per-plane blocks with loaded/expired cargo rows, Refuel-for-leg / Fly-to / Abandon + penalty preview) now renders in `components/LeftPane.tsx` between Fleet and Time — wallet stays on top. The JSX moved verbatim (same testids: `onboard-{planeId}`, `onboard-package-{pkg.id}`, `refuel-for-*`, `fly-to-*`, `abandon-*` + penalty preview), along with the `onboard` computation (`planes.filter(flying || slotsUsedFor > 0)`) and per-plane cargo filter. All onboard e2e locators are global testids, so existing specs work unchanged
|
||||||
|
- **Left pane widened: grid swapped to 360/1fr/280.** `.app-shell` in `app/globals.css` goes from `280px minmax(0, 1fr) 360px` to `360px minmax(0, 1fr) 280px` — total fixed width stays 640 px, so the map column is pixel-identical (map.spec.ts clicks via dynamic `map.project()`). Stale comments updated (on-board blocks now in the left pane; Relocate row comment reflects the 280 px right pane)
|
||||||
|
- **Shared action runner hook.** RightPane's local `runAction` (busy gate, inline pane error + shell toast on failure, full post-action snapshot pushed via `applySnapshot`) extracted to new `lib/useGameAction.ts`: `useGameAction(state, applySnapshot, onError) → { runAction, busy, actionError }`, exact semantics kept incl. the non-2xx throw/catch and inline-error auto-clear on the next snapshot. Used in BOTH panes; LeftPane receives `applySnapshot` from the shell (`app/page.tsx`). RightPane keeps `[data-testid="right-error"]`; LeftPane gains a matching `[data-testid="left-action-error"]`. Pure helpers `slotsUsedFor` / `loadEligiblePlanes` stay exported from RightPane (unit tests import them there; LeftPane imports `slotsUsedFor` from it); the Market Relocate row + `/api/airports` fetch stay in RightPane
|
||||||
|
- Tests: e2e — `panes.spec.ts` first test now also asserts the "On board" heading is visible inside `[data-testid="left-pane"]` and absent from the right pane; stale header comments updated in `actions.spec.ts` / `right-pane.spec.ts`. No unit-test changes (baseline 283)
|
||||||
|
- Verified: `tsc --noEmit` clean; unit suite green locally; e2e not run locally by design — CI verifies against an isolated stack
|
||||||
|
- **On-board cargo rows are two lines (ISS-028).** Each `onboard-package-*` row now stacks a full-width "Fly to <airport>" button on its own line above Refuel + Abandon side by side: `components/LeftPane.tsx` moves the fly-to button out of `.contract-main` into the row root and wraps refuel-for + abandon in a new `.onboard-actions` div — all testids, label text, penalty preview and disabled states unchanged. Long destination names in the fly-to label truncate with an ellipsis instead of overflowing: the label's inner span gets `min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap`, full name preserved via a `title` attribute (CSS in `app/globals.css`: `.onboard-block .contract-row` becomes flex-column, new `.onboard-fly-btn` / `.onboard-fly-label` / `.onboard-actions`). No e2e changes — specs locate everything by testid and assert no layout or button order; no version bump (part 2 of v0.20.0)
|
||||||
|
|
||||||
|
## v0.19.2 — 2026-09-19 20:06
|
||||||
|
- **AGENTS.md "Change process" item 1** — connected issues/tasks that reference the same part of code may now be done together on one branch/PR with a single version bump (e.g. two UI tweaks to the same panel)
|
||||||
|
- **AGENTS.md "E2E tests" section rewritten to match current reality** — e2e runs ONLY in CI, against an isolated docker stack inside dind (`docker-compose.ci.yml`); there are NO local e2e runs at all (local verification = `tsc --noEmit` + `npx vitest run` + `npx playwright test --list`; the full suite is verified by CI on every PR). Dropped the stale local-run instructions (deploying to the Traefik-routed instance before testing, driving browsers through the remote Playwright server at 192.168.1.4:3000); kept and reworded the CI env vars that actually exist in `playwright.config.ts` (`E2E_BASE_URL`, `E2E_DEPLOY_CMD`, `PW_REMOTE_BROWSER=0`, `E2E_COMPOSE_ARGS`)
|
||||||
|
|
||||||
|
## v0.19.1 — 2026-09-19 18:48
|
||||||
|
- AGENTS.md: document that CI-green is enforced on master by branch protection (required status check) and that merges use auto-merge (`merge_when_checks_succeed`) so PRs merge automatically once CI passes
|
||||||
|
|
||||||
|
## v0.19.0 — 2026-09-19 18:05
|
||||||
|
- **Auto-slow to 1× when all planes have landed (ISS-011).** When the last plane in flight lands, the sim slows down on its own so an idle fleet doesn't sit at 1000×. Server-side and authoritative: `tickOnce` (`lib/sim/engine.ts`) now remembers how many planes `deliverPackages` finalized during a tick, and when ≥1 plane landed this tick AND no plane remains with status `'flying'` AND the sim is not paused, it persists `timeScale = 1` on the same `sim_state` write as the clock — so the UI slider reflects it on the very next snapshot (no API or OpenAPI change: timeScale is still set via the existing `POST /api/sim`, and `clampTimeScale` semantics are untouched since 1 is a valid ladder value)
|
||||||
|
- **Arrival-triggered, not idle-enforced.** The trigger fires only on the tick that processes a landing — a grounded fleet at high scale with no flight ever happening is left alone (this keeps the existing slider e2e in `panes.spec.ts` green: it sets 1000× and expects the server to confirm it while nothing is flying). Paused state is untouched: while paused no landings are processed, so a paused sim never auto-slows
|
||||||
|
- **No auto-restore by design.** The previous scale is not remembered — once the game slows to 1× after the last landing, the player speeds up manually again (slider or `POST /api/sim`). Deliberately minimal scope: no "resume my old speed" behavior
|
||||||
|
- Tests: unit — new `describe('auto-slow …')` block in `lib/sim/engine.test.ts`: last plane lands → stored timeScale becomes 1; a landing while another plane is still flying → no change; already at 1× → stays 1; paused sim with all planes landed → no change. e2e — new `e2e/auto-slow.spec.ts` (serial mode, SCALE=1000, self-heal fly-home in afterEach like relocation.spec.ts): sets 1000× via the API, dispatches plane-starter on the shortest leg from its hub (EDDF → nearest airport), waits for the landing and asserts the server's `timeScale` is exactly 1 in that snapshot, then proves manual override still works (`POST /api/sim {timeScale: 1000}` confirmed by response + fresh snapshot)
|
||||||
|
- **e2e suite adapted to the new behavior.** Every existing spec that flies out-and-back relied on 1000× persisting across a landing — with ISS-011 it no longer does, so each return leg now re-sets SCALE explicitly: `flyHomeViaApi` in actions/relocation/right-pane/hover (re-set before the repositioning flight after waiting for an in-flight leg to land) and the restore legs inside the test bodies of actions.spec.ts (core loop, expired packages, validation paths ×2), right-pane.spec.ts (fly-to-destination, refuel-for-leg) and hover.spec.ts (flying-plane route highlight). map-interactions.spec.ts needed no change — its `loadAndFly` helper already re-sets SCALE before every landing wait
|
||||||
|
- Verified: `tsc --noEmit` clean; unit suite green locally; e2e not run locally by design — CI verifies against an isolated stack
|
||||||
|
|
||||||
|
## v0.18.0 — 2026-09-19 16:02
|
||||||
|
- **Relocate a grounded (empty) plane to any airport (ISS-010).** `flyPlane` has allowed pure repositioning since v0.12.0, but the UI only exposed flying for planes that carried cargo — an empty grounded plane had no fly control anywhere. Two new surfaces now drive the EXISTING `POST /api/planes/{id}/fly {destIcao}` endpoint (no API or OpenAPI change):
|
||||||
|
- **Right-pane market row** (`components/RightPane.tsx`): a fourth `.market-row` with `[data-testid="relocate-plane"]` (grounded planes, "ATR 72-600 — EDDF" labels), `[data-testid="relocate-dest"]` (all airports from a one-time `GET /api/airports` fetch per page life — same promise-ref pattern as Map.tsx — sorted by name for stable e2e selection) and the `[data-testid="relocate-go"]` "Relocate" button, disabled while busy or until both selects have a value. Same effective-selection + `runAction` pattern as the buy/sell/refuel rows (first grounded plane / first airport preselected); the row wraps (`market-row-relocate`) since two selects don't fit one 360 px line
|
||||||
|
- **Airport popup Relocate row** (`components/Map.tsx`): after the name/ICAO/local-time/weather lines, a `.popup-relocate` block with `[data-testid="airport-popup-plane"]` (grounded planes from the latest polled snapshot at click time) and `[data-testid="airport-popup-relocate"]` "Relocate here" — disabled until a plane is picked; on click it POSTs fly to the clicked airport, pushes the response snapshot through the shell's `applySnapshot` (new Map prop, same callback RightPane receives), and reports success/failure in `[data-testid="airport-popup-relocate-status"]`. With no grounded planes the row shows `[data-testid="airport-popup-no-planes"]` instead. Popups are plain HTML, not React — controls wired via `popup.getElement().querySelector(...)` after `.addTo(map)`
|
||||||
|
- **Bigger airport markers (ISS-010).** The r=3 dots were hard to click: `airports-circles` paint in `components/Map.tsx` goes from radius 3 / stroke 1 to radius 5 / stroke 1.5, and the hover highlight ring follows (r=8 → r=9). Paint-only — no data or interaction changes
|
||||||
|
- No server or OpenAPI changes — both surfaces reuse the existing fly endpoint (validations unchanged: 404 unknown plane / 409 flying or insufficient fuel / 400 unknown ICAO, strict unknown-field rejection kept)
|
||||||
|
- Tests: e2e — new `e2e/relocation.spec.ts` (serial mode, SCALE=1000, self-heal fly-home in afterEach like actions.spec.ts): market-row test ensures plane-starter grounded at the hub via API, picks it + the nearest non-hub airport (shortest leg) and asserts `/api/state` shows `flying` with that destIcao after clicking Relocate; popup test clicks the isolated LFRS marker (projected-center pattern from map.spec.ts), asserts the select lists "ATR 72-600 — EDDF" and the button is disabled until a plane is picked, then relocates via the popup. Marker-size regression gate = the existing map.spec.ts click tests keep passing
|
||||||
|
- Verified: `tsc --noEmit` clean; unit suite green locally (no lib/ changes — flyPlane's zero-package case already covered by actions.test.ts); e2e not run locally by design — CI verifies against an isolated stack
|
||||||
|
- **Fix (CI run #50): POPUP_AIRPORT scoping in the popup relocation e2e.** The LFRS marker click passed `POPUP_AIRPORT` into a `page.evaluate(() => …)` callback that runs in the BROWSER, where Node-scope constants don't exist — deterministic `ReferenceError: POPUP_AIRPORT is not defined` (relocation.spec.ts popup test, both attempts of run #50). The constant is now passed as an evaluate argument (`page.evaluate(({lon, lat}) => …, POPUP_AIRPORT)`); the other evaluate in the file only touches browser globals and needed no change. Test-only — no app code touched
|
||||||
|
- **Fix (CI run #51): strict-mode locator in the popup relocation e2e.** `expect(planeSel.locator('option')).toContainText(…)` resolved to BOTH options (placeholder + plane) → strict mode violation (relocation.spec.ts popup test, both attempts of run #51; the app rendered correctly). The assertion now targets `option[value="plane-starter"]` specifically with `toHaveText`. Test-only — no app code touched
|
||||||
|
|
||||||
|
## v0.17.0 — 2026-09-19 14:49
|
||||||
|
- **Bottom-right toasts for action errors (ISS-008).** Error messages like "insufficient funds: a ATR 72-600 costs 200000, you have 62721" now appear as toasts in the bottom-right corner — new `lib/useToasts.ts` hook (`useToasts() → {toasts, push(kind, msg), dismiss(id)}`, auto-dismiss after ~5 s, queue capped at 4 dropping the oldest; pure core `pushToast` unit-tested) and new `components/Toasts.tsx` `<ToastStack>` (fixed container `.toasts`, items `[data-testid="toast"]` with class `toast toast-error|toast-info` + a × dismiss button). Wired into BOTH error paths: `RightPane.runAction`'s catch now calls the shell's `onError` in addition to keeping the inline `[data-testid="right-error"]` pane error, and `LeftPane.applySimControls`'s catch (previously console.error-only) reports "Failed to update time controls (…)" through the same callback. The shell (`app/page.tsx`) owns the hook and renders the stack; CSS in `app/globals.css`
|
||||||
|
- **Event messages via snapshot diffing.** No server event feed exists, so new pure `lib/deriveEvents.ts` — `diffSnapshots(prev: StateSnapshot | null, next) → {kind:'info', message}[]` — derives human-readable events from the fields already in `/api/state`: plane landing (`flying→available`, "ATR 72-600 landed at Frankfurt"), package delivery (`loaded→delivered`, "Package delivered: +€X" with the reward), expiry (`open|loaded→expired`, "Package expired: A → B"), new packages (id only in next, "New package available: A → B") and planes bought/sold (plane id set changed, "Bought/Sold {model}"). The shell keeps a `prevRef` and diffs on every snapshot change, pushing each event as an info toast; the first snapshot after load emits nothing (no baseline — no page-load spam)
|
||||||
|
- **Browser notifications when the window is not focused.** Each derived event also fires `new Notification('Flight Ops', {body})` when `document.hidden && 'Notification' in window && Notification.permission === 'granted'`. The left-pane Time section gains an explicit opt-in button (`[data-testid="enable-notifications"]`) calling `Notification.requestPermission()`; its label reflects the result ("Enable notifications" → "Notifications enabled"/"Notifications blocked"), and it renders disabled with a tooltip title when the API is absent. SSR-safe: permission state starts null and is read in an effect after hydration
|
||||||
|
- No server or OpenAPI changes — diffing uses only existing snapshot fields (verified: planes by id/status/locationName, packages by id/status/reward/origin+dest names)
|
||||||
|
- Tests: unit — new `lib/deriveEvents.test.ts` suite pins every event format (landing, delivery with reward, expiry from open and loaded, new-package appearance, bought/sold, identical snapshots → [], first snapshot → [], non-events like takeoff/load ignored); `lib/useToasts.test.ts` covers the queue cap. e2e — new `e2e/toasts.spec.ts`: deterministic insufficient-funds path (select the most expensive model in `[data-testid="market-buy-model"]`, click Buy, expect a visible error toast matching /insufficient funds/ AND the inline `right-error` still showing; skips only if cash already covers the plane on a long-lived local instance) and the notifications opt-in (unsupported → disabled + title; otherwise fresh context shows "Enable notifications" and after clicking the label reflects the result — soft, since headless CI may deny permission)
|
||||||
|
- Verified: `tsc --noEmit` clean; unit suite green locally; e2e not run locally by design — CI verifies against an isolated stack
|
||||||
|
- **Fix (CI runs #44/#47): sim-control POSTs are retried before surfacing the error.** A dropped `POST /api/sim` on the runner's flaky uplink left the UI optimistic while the server kept the old scale — panes.spec.ts:74 timed out with timeScale stuck at 1000 (run #47). `applySimControls` now retries each commit up to 3× total (~500 ms backoff) before surfacing the error toast; a newer intent arriving mid-retry supersedes the in-flight body instead of waiting out its retries (last-wins queueing kept), and the endpoint's set-semantics make re-sending an already-applied value idempotent. Pure retry core `retrySimPost` exported from LeftPane + unit-tested. Also run #47: toasts.spec.ts Part B is now permission-state-aware — headless Chromium reports `Notification.permission` as 'denied' (not 'default'), so the test branches on the actual state (denied → assert blocked label without clicking; granted → enabled label; default → prompt, click, accept either resulting label)
|
||||||
|
|
||||||
|
## v0.16.1 — 2026-09-19 14:00
|
||||||
|
- **Smooth client-side sim clock with per-snapshot re-sync (ISS-007).** The left-pane "Time" display used to jump once per 1 s poll because it rendered the snapshot's `clockMs` verbatim. It now ticks smoothly on the client between polls: new hook `lib/useSimClock.ts` keeps an anchor `{clockMs, at, timeScale, paused}` and re-derives the display clock every ~100 ms as `anchor.clockMs + (now − at) × timeScale` — exactly the server's own tick model (`tickOnce`: real-time × timeScale), so client extrapolation mirrors authoritative game time. Every new snapshot re-anchors to server truth, bounding any drift by network latency only; while paused the display is frozen at the anchor value (advance 0). The pure core `advanceSimClock(anchor, nowMs)` is exported and unit-tested in node
|
||||||
|
- **LeftPane consumes it for the `sim-clock` paragraph ONLY** (`components/LeftPane.tsx`): fed with EFFECTIVE controls `{timeScale: pendingScale ?? snapshot scale, paused}` so a slider drag or pause click takes effect on click/drag without waiting for a confirming snapshot; the `(paused)` suffix keeps coming from the effective paused flag. Right-pane deadline/penalty previews are untouched — they stay computed from the snapshot's `clockMs` (deterministic against server truth)
|
||||||
|
- No server or OpenAPI changes — display-only client work
|
||||||
|
- Tests: unit — new suite in `lib/useSimClock.test.ts` pins the extrapolation math (exact elapsed × scale advance, frozen while paused at any scale, zero-elapsed identity, clock-skew clamp never goes backwards, mirrors the tickOnce formula under the 2 s clamp). e2e (`panes.spec.ts`) — new test: at scale 1000 sample `sim-clock` three times ~1.3 s apart real time and assert the displayed clock strictly advances between CONSECUTIVE samples (with poll-only rendering a pair could straddle zero snapshots and not change), plus format check and a total-advance sanity bound
|
||||||
|
- Verified: `tsc --noEmit` clean; unit suite green locally; e2e not run locally by design — CI verifies against an isolated stack
|
||||||
|
|
||||||
|
## v0.16.0 — 2026-09-19 12:18
|
||||||
|
- **Weight-proportional fuel burn (ISS-005, part A).** Fuel no longer burns at a constant L/km — the instantaneous rate is proportional to total weight, `r(F) = k·(We + ρF)` L/km with We the empty weight and ρ = 0.8 kg/L (Jet-A1), so a heavier plane burns more per km and a tank gets lighter as it empties. The constant `k` is calibrated so a FULL tank burns exactly the catalog's old `burnPerKm`, keeping full-tank departure behavior identical to before; divergence only grows in flight as fuel drops off. Closed forms of `dF/dx = −k(We + ρF)` live in `lib/sim/movement.ts` (single source of truth):
|
||||||
|
- `fuelAtWeighted(startFuel, burnPerKm, emptyWeightKg, maxFuel, distanceKm, progress)` — fuel remaining after flying `progress` of the leg (replaces the old constant-rate `fuelAt`, which is removed)
|
||||||
|
- `requiredFuelFor(burnPerKm, emptyWeightKg, maxFuel, distanceKm)` — liters needed to cover the distance arriving empty, independent of starting load; a leg is flyable iff current fuel ≥ this and fits at all iff it ≤ tank capacity
|
||||||
|
- `burnRateConstant(...)` + exported `FUEL_DENSITY_KG_PER_L` (0.8)
|
||||||
|
- **Catalog gains `emptyWeightKg`** (`lib/game/catalog.ts`, ATR 72-600 OEW ≈ 9300 kg), exposed in the snapshot's `catalog[]` so clients can mirror the model; OpenAPI `CatalogEntry` follows
|
||||||
|
- **All three burn call sites moved to the weighted model**: landing fuel on arrival (`lib/sim/engine.ts`), live in-flight fuel in the state snapshot (`lib/game/state.ts`), and fly validation (`lib/game/actions.ts` — a leg now needs `requiredFuelFor`, not `burnPerKm × km`)
|
||||||
|
- **Refuel "just enough for the loaded package" (ISS-005, part B).** `POST /api/planes/{planeId}/refuel` takes an OPTIONAL JSON body `{ mode?: 'full' | 'forFlight', packageId?: string }`: no body or `mode:'full'` is exactly today's fill-to-max behavior; `mode:'forFlight'` adds just enough fuel to fly that loaded package's destination leg — liters = `requiredFuelFor(haversine(plane → pkg.destIcao)) − current fuel`, 409 if the package isn't loaded on this plane / is expired, or the leg doesn't fit even a full tank; bad bodies (unknown field/mode, forFlight without packageId) are 400. OpenAPI gains `RefuelRequest` + the 400
|
||||||
|
- **UI** (`components/RightPane.tsx`): each on-board cargo row gets a "Refuel" button (`refuel-for-{pkg.id}` → `{mode:'forFlight', packageId}`, disabled while flying or busy, mirroring fly-to/abandon); the market fill-up button is renamed **"Refuel to full"** (testid `market-refuel` and behavior unchanged)
|
||||||
|
- Tests: unit — new weighted-burn suite in `lib/sim/movement.test.ts` (full-tank calibration ≈ old constant, closed form vs numeric integration of r(F), F_req monotonic + empty-arrival identity, lighter-start burns less, clamping); `refuelPlane` forFlight cases in `lib/game/actions.test.ts` (exact liters/cost, no-op when enough, 409 not-loaded/expired/doesn't-fit via the ~7670 km UNNT↔LPPD pair, 404 unknown package, 400 missing packageId); refuel route body-validation tests; `lib/openapi.test.ts` updated (optional RefuelRequest, errorCodes `['400','404','409']`, CatalogEntry.emptyWeightKg). Adjusted where the model legitimately shifts numbers: landing-fuel assertions in `lib/sim/engine.test.ts` and `e2e/actions.spec.ts` now use the weighted closed form; the e2e "return leg unfuelable" scenario is reworked — under weight-proportional burn a full tank covers the EDDF↔LEZL round trip (the plane lightens as it flies), so the 409 insufficient-fuel assertion moves to the SECOND outbound after landing back with a partial tank
|
||||||
|
- e2e (`right-pane.spec.ts`): new test — fly the longest hub leg on a full tank, load a package back to the hub at the far end, click the row "Refuel" and assert via the endpoint's own response snapshot that cash drops by exactly L×price and fuel rises by exactly L (L from the mirrored closed form); also asserts the market button label is "Refuel to full". `e2e/api.spec.ts` path list unchanged
|
||||||
|
- Verified: `tsc --noEmit` clean; unit suite green locally; e2e not run locally by design — CI verifies against an isolated stack
|
||||||
|
- **Fix (CI run #40): forFlight refuel leaves an exactly-feasible tank, and the new e2e's premise corrected.** The right-pane e2e picked the dataset's absolute farthest airport from EDDF — UNNT at ~4803 km, whose leg needs ~6955 L > the 6300 L tank (max range from empty is ~4436 km) — so the full-tank fly rightly 409'd; `farthestToHub` becomes `farthestFlyableToHub`, picking the farthest airport whose leg still fits a full tank (UWUU, ~3195 km). Server hardening in the same area: forFlight now sets fuel to EXACTLY `requiredFuelFor(...)` instead of `fuel + liters` — that sum is not guaranteed ≥ R in IEEE754 (`f + fl(R − f)` can round a hair below), and flyPlane's strict comparison would then 409 on an otherwise-feasible leg; cost math unchanged (still the added liters × price). New unit regression test: forFlight on an empty-ish tank → immediate `flyPlane` to the package destination succeeds
|
||||||
|
- **E2e flake hardening (runs #36/#41): full-core-loop Load/Fly precondition races** — test mechanics only, no app code changes. Two independent races in `e2e/actions.spec.ts`: (1) the Fly click fires its POST asynchronously (`runAction` is fire-and-forget from the test's view), so the immediate `getState` could race ahead of it and still see status 'available' — now an `expect.poll` waits until the server shows 'flying' with the expected destIcao before proceeding; (2) `flyHomeViaApi` made its repositioning decision from a snapshot taken BEFORE waiting for a leftover in-flight leg to land — while flying, locationIcao stays at the departure airport, so a plane that landed away from home was still believed to be home and never repositioned (run #41 retry: starter stranded at EDFH) — state is now re-read after landing; plus an explicit server-side precondition poll (starter grounded at the package origin) before clicking Load
|
||||||
|
|
||||||
|
## v0.15.1 — 2026-09-19 11:04
|
||||||
|
- **Right pane widened, "On board" wrapping fixed (ISS-004).** The 3-pane shell grid (`app/globals.css` `.app-shell`) moves from `300px / 1fr / 320px` to `280px / 1fr / 360px` — the map column absorbs the delta (MapLibre sizes itself from its container, no JS change). Three wrap offenders in the right pane's "On board" blocks are fixed:
|
||||||
|
- In-flight leg header (`components/RightPane.tsx`, `.contract-route` span): the class already had `white-space: nowrap; overflow: hidden; text-overflow: ellipsis`, but as a flex item with default `min-width: auto` it could not shrink below its full text width, so long routes (e.g. "Frankfurt → Madrid–Barajas") overflowed instead of ellipsizing — `.contract-route` now has `min-width: 0`
|
||||||
|
- Cargo-row buttons ("Fly to {dest}" / "Abandon −€X" in `.contract-main`): labels wrapped mid-text at the old width — `.pane-btn` now has `white-space: nowrap`
|
||||||
|
- Cargo sub-line route span had no white-space rule and wrapped mid-route — it now carries the existing `contract-route` class (nowrap + ellipsis)
|
||||||
|
- **Left pane sanity-checked at its new 280px**: fleet-row location span (`.plane-loc`) already had nowrap+ellipsis but lacked `min-width: 0`, so a long in-flight leg would have overflowed instead of truncating — same one-line guard added. Fuel/loadout spans are short fixed strings and need no guard
|
||||||
|
- Verified: `tsc --noEmit` clean; unit suite **238/238** green locally (no lib changes); e2e not run locally by design — CI verifies against an isolated stack
|
||||||
|
- **Unrelated test-stability fix included on this branch to unblock the pipeline** (`e2e/map-interactions.spec.ts`, no app changes): the mid-flight marker click now targets the plane's RENDERED position — it polls up to ~5 s for the rendered feature via `window.__flightMap.queryRenderedFeatures` on layers `planes-flying`/`planes-grounded` and projects that feature's coordinates, instead of fetching a fresh `/api/state`. With the sim paused the server position is static, but the map renders from its own ~1 s poll — right after the freeze confirmation the last rendered frame can still be up to one poll interval stale (tens of px at scale 1000 on EDDF→LEMD), so a click projected from a fresh fetch misses the small circle layer: the render-lag race that flaked CI run #37. Pause + freeze confirmation, popup assertions and resume are unchanged
|
||||||
|
|
||||||
## v0.15.0 — 2026-09-19 09:35
|
## v0.15.0 — 2026-09-19 09:35
|
||||||
- **Hover visualization from the side panels (ISS-002).** Hovering a fleet row in the left pane, an "On board" block (including its cargo rows) or an open-package row in the right pane now highlights the matching object on the map. The shared `HoverTarget` type (`components/hoverTypes.ts`: `{kind:'plane', id}` | `{kind:'package', originIcao, destIcao}`) is owned by the shell as a single `useState` and prop-drilled down — panes report via an `onHover` callback, `<Map>` consumes it. No React contexts introduced; the established prop-drilling pattern is kept
|
- **Hover visualization from the side panels (ISS-002).** Hovering a fleet row in the left pane, an "On board" block (including its cargo rows) or an open-package row in the right pane now highlights the matching object on the map. The shared `HoverTarget` type (`components/hoverTypes.ts`: `{kind:'plane', id}` | `{kind:'package', originIcao, destIcao}`) is owned by the shell as a single `useState` and prop-drilled down — panes report via an `onHover` callback, `<Map>` consumes it. No React contexts introduced; the established prop-drilling pattern is kept
|
||||||
- **Three top-most highlight layers** (`components/Map.tsx`, added inside idempotent `ensureLayers()` so they survive every `setStyle`): `planes-highlight` (circle over both plane layers, filter `['==',['get','id'],<planeId>]`, r=10, #38bdf8 fill + white stroke), `routes-highlight` (line over `routes-legs`, filter on the leg's `planeId`, width 6, #ef4444) and `airports-highlight` (circle ring over `airports-circles`, filter matching the hovered package's two ICAOs via `['any', …]`, r=8 stroke-only). All start filtered to match nothing — an empty-string sentinel no feature can have. Consumption follows the existing ref + effect pattern: a `[hovered]` effect calls `map.setFilter(...)` on the three layers (guarded by `getLayer`), and `ensureLayers` re-applies the current filter at its end so a hover outliving a style switch stays highlighted
|
- **Three top-most highlight layers** (`components/Map.tsx`, added inside idempotent `ensureLayers()` so they survive every `setStyle`): `planes-highlight` (circle over both plane layers, filter `['==',['get','id'],<planeId>]`, r=10, #38bdf8 fill + white stroke), `routes-highlight` (line over `routes-legs`, filter on the leg's `planeId`, width 6, #ef4444) and `airports-highlight` (circle ring over `airports-circles`, filter matching the hovered package's two ICAOs via `['any', …]`, r=8 stroke-only). All start filtered to match nothing — an empty-string sentinel no feature can have. Consumption follows the existing ref + effect pattern: a `[hovered]` effect calls `map.setFilter(...)` on the three layers (guarded by `getLayer`), and `ensureLayers` re-applies the current filter at its end so a hover outliving a style switch stays highlighted
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
# ORCHESTRATOR.md — Operating Manual for Successor Agents
|
||||||
|
|
||||||
|
You are taking over the autonomous development loop on **Flight-Ops** (browser game: run an airplane transport company in Europe; server-authoritative sim, MapLibre GL JS map). This document captures operational knowledge that is NOT written down in AGENTS.md. Read AGENTS.md first — it defines the mandatory change process and this file complements it.
|
||||||
|
|
||||||
|
Credentials are deliberately NOT stored in this file — see §1 for where they live. Never paste token values into any tracked file.
|
||||||
|
|
||||||
|
## 1. Project identity
|
||||||
|
- Repo: Gitea at https://git.kkhost.pl → org **OpenCode**, repo **Flight-Ops** (full name `OpenCode/Flight-Ops`). Every Gitea API/MCP call uses owner=`OpenCode`, repo=`Flight-Ops`.
|
||||||
|
- Local workdir + prod deploy dir: `/home/krzyw/projects/sandbox/flight` (git checkout; `docker compose up -d --build` deploys from here).
|
||||||
|
- Prod URL: https://flight.dev.kkhost.pl (Traefik → docker-compose stack on this host). `GET /api/version` reports the running version.
|
||||||
|
- Gitea API access for git.kkhost.pl: prefer the gitea MCP tools — they are already configured with a token. For raw REST/curl, read the current token from the local .env file at repo root (variable `GITEA_TOKEN`; .env is gitignored and must never be committed): `source .env && curl -s -H "Authorization: token $GITEA_TOKEN" https://git.kkhost.pl/api/v1/user`. (Incident note, Sept 2026: an early draft of this doc committed a live token to the repo; that commit was purged from all refs and the token has since been rotated — never repeat this.)
|
||||||
|
- Current user: kamilkrzywda (id 1).
|
||||||
|
|
||||||
|
## 2. The loop (per issue)
|
||||||
|
1. Small incremental change on a feature branch off `master`; connected issues may share one branch/PR with a single version bump.
|
||||||
|
2. Bump `package.json` version + add CHANGELOG.md entry at top: `## v<version> — YYYY-MM-DD HH:MM` then bullet points of what changed (docs-only changes get patch bumps too — precedent v0.19.1/v0.19.2).
|
||||||
|
3. Local verification ONLY (there are NO local e2e runs): `npx tsc --noEmit`, `npx vitest run` (the whole unit suite must pass — the test count grows over time, so compare against the previous green run, never a hardcoded number), `npx playwright test --list` (all specs compile and list).
|
||||||
|
4. Push → CI (~7 min) → **auto-merge on green** (PRs have auto-merge configured; no manual merge needed — verify via `GET /pulls/{n}` that state=closed and merged_at is set). Note: if a PR was created via API rather than create-on-push, double-check auto-merge actually fires.
|
||||||
|
5. Tag the version on master: `git tag v<version> origin/master && git push origin v<version>` (after `git fetch origin master`).
|
||||||
|
6. Deploy prod in a PTY (long task): `cd /home/krzyw/projects/sandbox/flight && git checkout master && git reset --hard origin/master && docker compose up -d --build`; then verify `curl https://flight.dev.kkhost.pl/api/version` returns the new version and the root page is HTTP 200.
|
||||||
|
7. Close each issue with a comment: what changed, version, PR number, merge commit SHA, deployed URL.
|
||||||
|
8. Repeat for the next open issue: `GET /issues?state=open&type=issues` — note Gitea lists pull requests in this endpoint too; filter out entries with a `pull_request` key.
|
||||||
|
|
||||||
|
## 3. Gitea API + MCP quirks (learned the hard way)
|
||||||
|
- The gitea MCP tools work for issues/PRs/files/tags, and Actions endpoints work IF you pass owner=`OpenCode`, repo=`Flight-Ops`. A wrong owner/repo makes EVERY call return `{"message":"not found","url":"https://git.kkhost.pl/api/swagger"}` — that swagger URL inside a 404 is the signature of "wrong path", not "Gitea is down".
|
||||||
|
- MCP merge endpoint 405s → don't bother; auto-merge handles merging. Manual fallback if ever needed: `POST /repos/OpenCode/Flight-Ops/pulls/{n}/merge` with body `{"do":"merge","merge_style":"merge"}`.
|
||||||
|
- Gitea REST shapes (NOT GitHub's): list runs → `{workflow_runs:[...]}`; run jobs → `/actions/runs/{id}/jobs` returns `{"jobs":[...]}`; single job log via MCP `get_job_log_preview` (param tail_lines) or `download_job_log` to a file, then grep.
|
||||||
|
- Failure anatomy in CI logs: the Playwright summary at the end lists "N failed" + test titles; each failure block has a code frame with line numbers plus an "Error Context:" path. The e2e step is the only one that can fail flakily; unit failures are real regressions.
|
||||||
|
- CI watcher pattern that works: `run_background_process` (notify=true) running a loop that polls `GET /actions/runs/{id}` every 60 s and exits when status=completed, printing status+conclusion each tick. Don't poll in the foreground; don't sleep-loop on pty_read.
|
||||||
|
|
||||||
|
## 4. CI facts (.gitea/workflows/ci.yml + docker-compose.ci.yml)
|
||||||
|
- Single job "build + unit + e2e" on runner gitea-runner (docker-in-docker). Fresh DB per run (volume removed); compose project `flight-ci`; app container on a static IP → `E2E_BASE_URL=http://172.39.0.10:3000`; `PW_REMOTE_BROWSER=0` (CI runs local chromium — the shared remote browser server at 192.168.1.4 cannot reach a stack inside dind); `E2E_COMPOSE_ARGS="-f docker-compose.ci.yml -p flight-ci"` is read by e2e/state.spec.ts for its mid-run `docker compose restart flight`.
|
||||||
|
- Flaky uplink → retry loops in ci.yml; an occasional "flaky" test (failed once, passed on retry) does NOT fail the run.
|
||||||
|
- Branch protection requires status check `CI / build + unit + e2e (pull request)` — PRs cannot merge until green; CI never deploys to production.
|
||||||
|
|
||||||
|
## 5. E2E conventions (e2e/*.spec.ts) — read before touching tests
|
||||||
|
- Sim scale in tests: SCALE=1000; hub `HUB='EDDF'` (Frankfurt); typical destination LEMD.
|
||||||
|
- `flyHomeViaApi(page)` self-heal at test start — interrupted runs can leave planes mid-flight; landing waits up to 240 s.
|
||||||
|
- Pause-sim pattern for deterministic marker clicks: pause, act, assert, resume.
|
||||||
|
- Dev hook: `window.__flightMap` exposes the live MapLibre map instance in dev builds (also `__flightLastSnapshot`).
|
||||||
|
- `queryRenderedFeatures` is viewport-scoped → fitBounds/fitToAirports before asserting on far features; give the renderer ~300 ms after a camera jump.
|
||||||
|
- **expect.poll callbacks must be total** — a throw inside fails the test instantly instead of retrying. Guard/filter everything you dereference.
|
||||||
|
|
||||||
|
## 6. ⚠️ The big one: Playwright evaluate serialization drops prototype getters
|
||||||
|
MapLibre's `queryRenderedFeatures` returns live `GeoJSONFeature` class instances whose `geometry` is a **lazy PROTOTYPE getter** (own properties are only type/properties/id/source/state plus private fields). Playwright serializes evaluate results by copying **own enumerable properties only**, so every feature arriving in test context has NO geometry — silently.
|
||||||
|
- Verified empirically: `page.evaluate(() => { class A{constructor(){this.own=1} get geo(){return 42}} return [new A()] })` → `[{"own":1}]`.
|
||||||
|
- Symptom matrix (how it masqueraded as "the line isn't drawn" while the trace rendered fine on screen, across three consecutive failed CI runs in Sept 2026): strict length guard → timeout; direct `.geometry.coordinates` access → `TypeError: Cannot read properties of undefined (reading 'coordinates')`; defensive filter → clean 15 s timeout.
|
||||||
|
- **Rule: never return maplibre feature instances across page.evaluate — always map to plain objects in-page** (`{type, id, properties, geometry: f.geometry}` forces the getter to evaluate). Canonical pattern: `renderedFeatures()` in e2e/hover.spec.ts. Other specs that touch `.geometry` do so inside evaluate (safe) or only read array length (safe).
|
||||||
|
|
||||||
|
## 7. MapLibre rendering facts (for map assertions)
|
||||||
|
- GeoJSON geometry is stored per-tile in INTEGER grids; long lines are clipped → `queryRenderedFeatures` returns ONE FEATURE PER TILE the line crosses (the EDDF→LEMD leg ≈ 4–5 segments at z=4/5).
|
||||||
|
- Coordinates are quantized to the grid: error up to ~half a grid step (~0.001° observed at z≥4, worst ~0.02° at z=0 with extent 8192). Endpoint assertions must use an EPS sized for this (the hover tests define one in `expectHoverRoute` in e2e/hover.spec.ts — ~5 km: above worst-case quantization at any zoom, below the distance between any two EU airports) and check endpoints ACROSS ALL SEGMENTS: some segment must START within EPS of origin AND some must END within EPS of destination. Never strict equality on a single feature.
|
||||||
|
- The true line endpoints survive clipping verbatim in whichever tile contains them.
|
||||||
|
|
||||||
|
## 8. App architecture quick map
|
||||||
|
- `components/Map.tsx` — the MapLibre layer: sources/layers created in ensureLayers (dedicated `hover-routes` GeoJSON source + top-most dashed `hover-route` LineLayer, plus an `airports-target-highlight` ring layer added last so it sits above the line at its endpoint — current colors/widths live in Map.tsx, don't trust this doc for exact paint values); applyHoverRef re-pushes data on every hover; `window.__flightMap` dev hook.
|
||||||
|
- `lib/mapData.ts` — pure GeoJSON builders (`hoverRouteGeoJson`, `routesGeoJson`, `greatCircleArc` slerp) + unit tests in lib/mapData.test.ts.
|
||||||
|
- Hover protocol: panes report a HoverTarget via mouseenter/leave (`components/hoverTypes.ts`): `{kind:'plane';id} | {kind:'package';originIcao;destIcao;planeId?} | {kind:'route';fromIcao;toIcao}`; the `''` sentinel means no hover.
|
||||||
|
- Server: sim ticks server-side, client polls /api/state; OpenAPI spec generated from lib/openapi.ts and served at /api/openapi — update it whenever an endpoint changes.
|
||||||
|
|
||||||
|
## 9. Finding current state (this file keeps no snapshots)
|
||||||
|
This manual is meant to stay valid long-term, so it deliberately contains NO version or issue snapshots — they rot. To orient yourself when you take over: `git log --oneline -10` + CHANGELOG.md for what has shipped; `GET /issues?state=open&type=issues` (filter out entries with a `pull_request` key) for what is left to do; PLAN.md's "Later" section for the roadmap backlog.
|
||||||
|
|
||||||
|
## 10. Standing user instruction & etiquette
|
||||||
|
- The user's standing order for this project: work through the issue list autonomously — implement → PR → CI green → merge → tag → deploy prod → close with comment → next — until told to stop.
|
||||||
|
- Small incremental changes; each part fully tested (unit + e2e) before moving on.
|
||||||
|
- Long terminal tasks → pty_* tools (deploys, builds). Background watchers → run_background_process with notify=true.
|
||||||
|
- Never push directly to master; never deploy from a feature branch; CI never touches prod — production deploys are manual only (`docker compose up -d --build` after tagging).
|
||||||
|
- **Never commit credentials.** Tokens/secrets live in the MCP server config or with the user, never in tracked files (see incident note in §1).
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { ignorePackage, performAction } from '@/lib/game/actions';
|
||||||
|
|
||||||
|
// POST /api/packages/:id/ignore (v0.29.0, ISS-047 part B) — no body. Dismisses an OPEN job so it
|
||||||
|
// leaves the market permanently; the top-up logic spawns a replacement on the next tick. No penalty,
|
||||||
|
// nothing else changes. 404 unknown id; 409 unless open. On success returns the full state snapshot.
|
||||||
|
|
||||||
|
export async function POST(_req: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||||
|
const { id } = await ctx.params;
|
||||||
|
return performAction((inst) => ignorePackage(inst, id));
|
||||||
|
}
|
||||||
@@ -1,10 +1,11 @@
|
|||||||
import { loadPackage, performAction } from '@/lib/game/actions';
|
import { loadPackage, performAction } from '@/lib/game/actions';
|
||||||
|
|
||||||
// POST /api/packages/:id/load (v0.12.0) — body { planeId: string }. Loads an OPEN
|
// POST /api/packages/:id/load (v0.12.0) — body { planeId: string }. Loads an OPEN
|
||||||
// package onto a GROUNDED plane at the package's origin with a free slot. 400
|
// package onto a GROUNDED plane at the package's origin with enough payload room
|
||||||
// missing/non-string planeId or unknown fields; 404 unknown package/plane id; 409
|
// for its weight (v0.27.0). 400 missing/non-string planeId or unknown fields; 404
|
||||||
// wrong package status, plane flying, plane not at the origin, no free slots. On
|
// unknown package/plane id; 409 wrong package status, plane flying, plane not at
|
||||||
// success returns the full state snapshot (package now "loaded" on that plane).
|
// the origin, no payload room. On success returns the full state snapshot
|
||||||
|
// (package now "loaded" on that plane).
|
||||||
|
|
||||||
export async function POST(req: Request, ctx: { params: Promise<{ id: string }> }) {
|
export async function POST(req: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||||
const { id } = await ctx.params;
|
const { id } = await ctx.params;
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { cancelQueuedLeg, performAction } from '@/lib/game/actions';
|
||||||
|
|
||||||
|
// POST /api/planes/:planeId/queue/cancel (v0.25.0, ISS-043) — body { index: number }.
|
||||||
|
// Removes a NOT-yet-started leg from the plane's queue by index; only queued legs
|
||||||
|
// are cancellable, the active in-flight leg is never affected. 400 missing/
|
||||||
|
// non-integer index, unknown fields, or an index outside [0, queue.length); 404
|
||||||
|
// unknown plane id. On success returns the full state snapshot (plane.queue updated).
|
||||||
|
|
||||||
|
export async function POST(req: Request, ctx: { params: Promise<{ planeId: string }> }) {
|
||||||
|
const { planeId } = await ctx.params;
|
||||||
|
|
||||||
|
let body: unknown;
|
||||||
|
try {
|
||||||
|
const text = await req.text();
|
||||||
|
body = text ? JSON.parse(text) : {};
|
||||||
|
} catch {
|
||||||
|
return Response.json({ error: 'invalid JSON body' }, { status: 400 });
|
||||||
|
}
|
||||||
|
if (typeof body !== 'object' || body === null || Array.isArray(body)) {
|
||||||
|
return Response.json({ error: 'body must be a JSON object' }, { status: 400 });
|
||||||
|
}
|
||||||
|
const input = body as Record<string, unknown>;
|
||||||
|
for (const key of Object.keys(input)) {
|
||||||
|
if (key !== 'index') {
|
||||||
|
return Response.json({ error: `unknown field "${key}"` }, { status: 400 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!Number.isInteger(input.index)) {
|
||||||
|
return Response.json({ error: 'index must be an integer' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const index = input.index as number;
|
||||||
|
return performAction((inst) => cancelQueuedLeg(inst, planeId, index));
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import { performAction, queueLeg } from '@/lib/game/actions';
|
||||||
|
|
||||||
|
// POST /api/planes/:planeId/queue (v0.25.0, ISS-043) — body { destIcao: string }.
|
||||||
|
// Appends a NOT-yet-started leg to the plane's flight queue; works whether the
|
||||||
|
// plane is grounded or flying (pre-building a route). Nothing auto-starts here —
|
||||||
|
// queued legs chain on landing when fuel covers them. 400 missing/non-string
|
||||||
|
// destIcao, unknown fields, or an ICAO not in the airport dataset; 404 unknown
|
||||||
|
// plane id. On success returns the full state snapshot (plane.queue updated).
|
||||||
|
|
||||||
|
export async function POST(req: Request, ctx: { params: Promise<{ planeId: string }> }) {
|
||||||
|
const { planeId } = await ctx.params;
|
||||||
|
|
||||||
|
let body: unknown;
|
||||||
|
try {
|
||||||
|
const text = await req.text();
|
||||||
|
body = text ? JSON.parse(text) : {};
|
||||||
|
} catch {
|
||||||
|
return Response.json({ error: 'invalid JSON body' }, { status: 400 });
|
||||||
|
}
|
||||||
|
if (typeof body !== 'object' || body === null || Array.isArray(body)) {
|
||||||
|
return Response.json({ error: 'body must be a JSON object' }, { status: 400 });
|
||||||
|
}
|
||||||
|
const input = body as Record<string, unknown>;
|
||||||
|
for (const key of Object.keys(input)) {
|
||||||
|
if (key !== 'destIcao') {
|
||||||
|
return Response.json({ error: `unknown field "${key}"` }, { status: 400 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (typeof input.destIcao !== 'string' || input.destIcao.length === 0) {
|
||||||
|
return Response.json({ error: 'destIcao must be a non-empty string' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const destIcao = input.destIcao;
|
||||||
|
return performAction((inst) => queueLeg(inst, planeId, destIcao));
|
||||||
|
}
|
||||||
@@ -5,7 +5,11 @@ import { eq } from 'drizzle-orm';
|
|||||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||||
import * as schema from '@/lib/db/schema';
|
import * as schema from '@/lib/db/schema';
|
||||||
import { getGameDb } from '@/lib/db/client';
|
import { getGameDb } from '@/lib/db/client';
|
||||||
|
import { loadAirportsGeoJson } from '@/lib/airports';
|
||||||
|
import { haversineKm } from '@/lib/geo';
|
||||||
|
import { requiredFuelFor } from '@/lib/sim/movement';
|
||||||
import { FUEL_PRICE_PER_L, PLANE_TYPES } from '@/lib/game/catalog';
|
import { FUEL_PRICE_PER_L, PLANE_TYPES } from '@/lib/game/catalog';
|
||||||
|
import { HUB_ICAO } from '@/lib/game/seed';
|
||||||
import { POST } from './route';
|
import { POST } from './route';
|
||||||
|
|
||||||
let dir: string;
|
let dir: string;
|
||||||
@@ -22,7 +26,15 @@ afterAll(async () => {
|
|||||||
await fs.rm(dir, { recursive: true, force: true });
|
await fs.rm(dir, { recursive: true, force: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
const post = (planeId: string) => POST(new Request(`http://localhost/api/planes/${planeId}/refuel`), { params: Promise.resolve({ planeId }) });
|
const post = (planeId: string, body?: unknown) =>
|
||||||
|
POST(
|
||||||
|
new Request(`http://localhost/api/planes/${planeId}/refuel`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: body === undefined ? undefined : JSON.stringify(body),
|
||||||
|
}),
|
||||||
|
{ params: Promise.resolve({ planeId }) },
|
||||||
|
);
|
||||||
|
|
||||||
describe('POST /api/planes/:planeId/refuel', () => {
|
describe('POST /api/planes/:planeId/refuel', () => {
|
||||||
it('rejects an unknown id with 404', async () => {
|
it('rejects an unknown id with 404', async () => {
|
||||||
@@ -74,4 +86,76 @@ describe('POST /api/planes/:planeId/refuel', () => {
|
|||||||
expect(res.status).toBe(409);
|
expect(res.status).toBe(409);
|
||||||
expect(((await res.json()) as { error: string }).error).toMatch(/insufficient funds/i);
|
expect(((await res.json()) as { error: string }).error).toMatch(/insufficient funds/i);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('accepts an explicit {mode:"full"} body exactly like no body', async () => {
|
||||||
|
const { db } = await getGameDb();
|
||||||
|
await db.update(schema.account).set({ cash: 50_000 }); // previous test left the account poor
|
||||||
|
await db.update(schema.planes).set({ fuel: 1_000 }).where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
|
const res = await post('plane-starter', { mode: 'full' });
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const body = (await res.json()) as { planes: Array<{ id: string; fuel: number }> };
|
||||||
|
expect(body.planes.find((p) => p.id === 'plane-starter')!.fuel).toBe(PLANE_TYPES.atr72.maxFuel);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects an unknown mode with 400', async () => {
|
||||||
|
const res = await post('plane-starter', { mode: 'half' });
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
expect(((await res.json()) as { error: string }).error).toMatch(/mode/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects forFlight without a packageId with 400', async () => {
|
||||||
|
const res = await post('plane-starter', { mode: 'forFlight' });
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
expect(((await res.json()) as { error: string }).error).toMatch(/packageId/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects an unknown body field with 400', async () => {
|
||||||
|
const res = await post('plane-starter', { liters: 100 });
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
expect(((await res.json()) as { error: string }).error).toMatch(/unknown field/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects invalid JSON with 400', async () => {
|
||||||
|
const res = await POST(
|
||||||
|
new Request(`http://localhost/api/planes/plane-starter/refuel`, { method: 'POST', body: '{nope' }),
|
||||||
|
{ params: Promise.resolve({ planeId: 'plane-starter' }) },
|
||||||
|
);
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('forFlight tops up exactly the liters needed for the loaded package leg', async () => {
|
||||||
|
const { db } = await getGameDb();
|
||||||
|
await db.update(schema.account).set({ cash: 50_000 });
|
||||||
|
// A loaded EDDF → LEMD package on the starter (direct row — loadPackage is covered in actions tests).
|
||||||
|
await db.insert(schema.packages).values({
|
||||||
|
id: 'p-ff-api', originIcao: HUB_ICAO, destIcao: 'LEMD', reward: 1_000, cargoType: 'Mail', cargoCount: 4,
|
||||||
|
deadlineSimTime: Date.now() + 24 * 3_600_000, status: 'loaded', planeId: 'plane-starter', createdSimTime: Date.now(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const fc = await loadAirportsGeoJson();
|
||||||
|
const from = fc.features.find((f) => f.properties.icao === HUB_ICAO)!.properties;
|
||||||
|
const to = fc.features.find((f) => f.properties.icao === 'LEMD')!.properties;
|
||||||
|
const km = haversineKm(from.lat, from.lon, to.lat, to.lon);
|
||||||
|
const type = PLANE_TYPES.atr72;
|
||||||
|
const required = requiredFuelFor(type.burnPerKm, type.emptyWeightKg, type.maxFuel, km);
|
||||||
|
|
||||||
|
const startFuel = Math.round(required / 2); // partial tank so L > 0
|
||||||
|
await db.update(schema.planes).set({ fuel: startFuel }).where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
const cashBefore = (await db.select().from(schema.account))[0].cash;
|
||||||
|
|
||||||
|
const res = await post('plane-starter', { mode: 'forFlight', packageId: 'p-ff-api' });
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
|
||||||
|
const body = (await res.json()) as {
|
||||||
|
account: { cash: number };
|
||||||
|
planes: Array<{ id: string; fuel: number }>;
|
||||||
|
};
|
||||||
|
const cost = Math.round((required - startFuel) * FUEL_PRICE_PER_L * 100) / 100;
|
||||||
|
expect(body.account.cash).toBeCloseTo(cashBefore - cost, 6);
|
||||||
|
expect(body.planes.find((p) => p.id === 'plane-starter')!.fuel).toBeCloseTo(required, 6);
|
||||||
|
|
||||||
|
// Clean up the test package.
|
||||||
|
await db.delete(schema.packages).where(eq(schema.packages.id, 'p-ff-api'));
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,11 +1,47 @@
|
|||||||
import { performAction, refuelPlane } from '@/lib/game/actions';
|
import { performAction, refuelPlane } from '@/lib/game/actions';
|
||||||
|
|
||||||
// POST /api/planes/:planeId/refuel (v0.8.0) — no body. Fills a grounded plane to
|
// POST /api/planes/:planeId/refuel (v0.8.0; optional body v0.16.0) — fills a grounded
|
||||||
// maxFuel at the fuel price per missing liter; deducts the cost from cash. 404
|
// plane at the fuel price per added liter and deducts the cost from cash. The body is
|
||||||
// unknown id; 409 if the plane is flying or cash is insufficient. On success
|
// OPTIONAL: no body, {} or {mode:'full'} fill to maxFuel (the original behavior);
|
||||||
// returns the full state snapshot (fuel back to max, cash reduced by the cost).
|
// {mode:'forFlight', packageId} adds just enough for that loaded package's destination
|
||||||
|
// leg. 400 bad body (unknown field, unknown mode, forFlight without packageId); 404
|
||||||
|
// unknown plane/package id; 409 if the plane is flying, the package isn't loaded on it
|
||||||
|
// (or is expired), the leg doesn't fit a full tank, or cash is insufficient. On success
|
||||||
|
// returns the full state snapshot (fuel raised by exactly the added liters).
|
||||||
|
|
||||||
export async function POST(_req: Request, ctx: { params: Promise<{ planeId: string }> }) {
|
export async function POST(req: Request, ctx: { params: Promise<{ planeId: string }> }) {
|
||||||
const { planeId } = await ctx.params;
|
const { planeId } = await ctx.params;
|
||||||
return performAction((inst) => refuelPlane(inst, planeId));
|
|
||||||
|
let body: unknown;
|
||||||
|
try {
|
||||||
|
const text = await req.text();
|
||||||
|
body = text ? JSON.parse(text) : {};
|
||||||
|
} catch {
|
||||||
|
return Response.json({ error: 'invalid JSON body' }, { status: 400 });
|
||||||
|
}
|
||||||
|
if (typeof body !== 'object' || body === null || Array.isArray(body)) {
|
||||||
|
return Response.json({ error: 'body must be a JSON object' }, { status: 400 });
|
||||||
|
}
|
||||||
|
const input = body as Record<string, unknown>;
|
||||||
|
for (const key of Object.keys(input)) {
|
||||||
|
if (key !== 'mode' && key !== 'packageId') {
|
||||||
|
return Response.json({ error: `unknown field "${key}"` }, { status: 400 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const mode = input.mode ?? 'full';
|
||||||
|
if (mode !== 'full' && mode !== 'forFlight') {
|
||||||
|
return Response.json({ error: 'mode must be "full" or "forFlight"' }, { status: 400 });
|
||||||
|
}
|
||||||
|
let packageId: string | undefined;
|
||||||
|
if (input.packageId !== undefined) {
|
||||||
|
if (typeof input.packageId !== 'string' || input.packageId.length === 0) {
|
||||||
|
return Response.json({ error: 'packageId must be a non-empty string' }, { status: 400 });
|
||||||
|
}
|
||||||
|
packageId = input.packageId;
|
||||||
|
}
|
||||||
|
if (mode === 'forFlight' && !packageId) {
|
||||||
|
return Response.json({ error: 'packageId is required when mode is "forFlight"' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
return performAction((inst) => refuelPlane(inst, planeId, { mode, packageId }));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import fs from 'node:fs/promises';
|
|||||||
import os from 'node:os';
|
import os from 'node:os';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||||
|
import { getGameDb } from '@/lib/db/client';
|
||||||
|
import * as schema from '@/lib/db/schema';
|
||||||
import { POST } from './route';
|
import { POST } from './route';
|
||||||
|
|
||||||
let dir: string;
|
let dir: string;
|
||||||
@@ -84,6 +86,21 @@ describe('POST /api/sim', () => {
|
|||||||
await post({ timeScale: 1, paused: false }); // restore
|
await post({ timeScale: 1, paused: false }); // restore
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('records lastSelectedTimeScale when timeScale is posted; a paused-only post leaves it untouched (ISS-057)', async () => {
|
||||||
|
const inst = await getGameDb(); // same singleton the route's applyTimeControls writes through
|
||||||
|
const row = async () => (await inst.db.select().from(schema.simState))[0];
|
||||||
|
|
||||||
|
await post({ timeScale: 250 });
|
||||||
|
expect((await row()).lastSelectedTimeScale).toBe(250); // manual intent recorded…
|
||||||
|
|
||||||
|
await post({ paused: true });
|
||||||
|
expect((await row()).paused).toBe(true);
|
||||||
|
expect((await row()).lastSelectedTimeScale).toBe(250); // …and a {paused}-only post does not touch it
|
||||||
|
|
||||||
|
await post({ timeScale: 1, paused: false }); // restore
|
||||||
|
expect((await row()).lastSelectedTimeScale).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
it('rejects invalid input with 400', async () => {
|
it('rejects invalid input with 400', async () => {
|
||||||
for (const body of [{ timeScale: 'fast' }, { timeScale: Infinity }, { paused: 'yes' }, { bogus: 1 }]) {
|
for (const body of [{ timeScale: 'fast' }, { timeScale: Infinity }, { paused: 'yes' }, { bogus: 1 }]) {
|
||||||
const res = await post(body);
|
const res = await post(body);
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ describe('GET /api/state', () => {
|
|||||||
|
|
||||||
const packages = body.packages as Array<Record<string, unknown>>;
|
const packages = body.packages as Array<Record<string, unknown>>;
|
||||||
expect(packages.length).toBeGreaterThan(0);
|
expect(packages.length).toBeGreaterThan(0);
|
||||||
for (const key of ['id', 'originIcao', 'destIcao', 'reward', 'cargoType', 'deadlineSimTime', 'status']) {
|
for (const key of ['id', 'originIcao', 'destIcao', 'reward', 'cargoType', 'weightKg', 'deadlineSimTime', 'status']) {
|
||||||
expect(packages[0], `package.${key}`).toHaveProperty(key);
|
expect(packages[0], `package.${key}`).toHaveProperty(key);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -86,7 +86,7 @@ describe('GET /api/state', () => {
|
|||||||
expect(entry.maxFuel).toBe(type.maxFuel);
|
expect(entry.maxFuel).toBe(type.maxFuel);
|
||||||
expect(entry.burnPerKm).toBe(type.burnPerKm);
|
expect(entry.burnPerKm).toBe(type.burnPerKm);
|
||||||
expect(entry.speedKmh).toBe(type.speedKmh);
|
expect(entry.speedKmh).toBe(type.speedKmh);
|
||||||
expect(entry.capacity).toBe(type.capacity); // v0.12.0 slot capacity (ATR 72-600: 6)
|
expect(entry.maxPayloadKg).toBe(type.maxPayloadKg); // v0.27.0 payload kg (ATR 72-600: 4800)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Economy constants — the single source of truth stays lib/game/catalog.ts.
|
// Economy constants — the single source of truth stays lib/game/catalog.ts.
|
||||||
|
|||||||
@@ -14,11 +14,13 @@ import { tickNow } from '@/lib/sim/engine';
|
|||||||
// same gate, same conventions.
|
// same gate, same conventions.
|
||||||
//
|
//
|
||||||
// POST /api/test/create-package
|
// POST /api/test/create-package
|
||||||
// body { originIcao?: string, destIcao?: string, deadlineOffsetMs?: number }
|
// body { originIcao?: string, destIcao?: string, deadlineOffsetMs?: number, weightKg?: number }
|
||||||
// - ICACOs must exist in the airport dataset and differ (400 otherwise);
|
// - ICACOs must exist in the airport dataset and differ (400 otherwise);
|
||||||
// omitted endpoints are picked at random by generatePackage.
|
// omitted endpoints are picked at random by generatePackage.
|
||||||
// - deadlineOffsetMs defaults to a normal 6–72h game-time window (NOT the short
|
// - deadlineOffsetMs defaults to a normal 6–72h game-time window (NOT the short
|
||||||
// hook deadline of expire-package) — pass an explicit value to override.
|
// hook deadline of expire-package) — pass an explicit value to override.
|
||||||
|
// - weightKg (v0.27.0) forces the package weight instead of the RNG draw, so e2e
|
||||||
|
// flows that load several packages can stay under the plane's payload deterministically.
|
||||||
// Returns 201 + the created package row.
|
// Returns 201 + the created package row.
|
||||||
|
|
||||||
export async function POST(req: Request) {
|
export async function POST(req: Request) {
|
||||||
@@ -38,7 +40,7 @@ export async function POST(req: Request) {
|
|||||||
}
|
}
|
||||||
const input = body as Record<string, unknown>;
|
const input = body as Record<string, unknown>;
|
||||||
for (const key of Object.keys(input)) {
|
for (const key of Object.keys(input)) {
|
||||||
if (key !== 'originIcao' && key !== 'destIcao' && key !== 'deadlineOffsetMs') {
|
if (key !== 'originIcao' && key !== 'destIcao' && key !== 'deadlineOffsetMs' && key !== 'weightKg') {
|
||||||
return Response.json({ error: `unknown field "${key}"` }, { status: 400 });
|
return Response.json({ error: `unknown field "${key}"` }, { status: 400 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -50,6 +52,9 @@ export async function POST(req: Request) {
|
|||||||
if (input.deadlineOffsetMs !== undefined && (typeof input.deadlineOffsetMs !== 'number' || !Number.isFinite(input.deadlineOffsetMs))) {
|
if (input.deadlineOffsetMs !== undefined && (typeof input.deadlineOffsetMs !== 'number' || !Number.isFinite(input.deadlineOffsetMs))) {
|
||||||
return Response.json({ error: 'deadlineOffsetMs must be a finite number' }, { status: 400 });
|
return Response.json({ error: 'deadlineOffsetMs must be a finite number' }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
if (input.weightKg !== undefined && (typeof input.weightKg !== 'number' || !Number.isFinite(input.weightKg) || input.weightKg <= 0)) {
|
||||||
|
return Response.json({ error: 'weightKg must be a positive finite number' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const inst = await getGameDb();
|
const inst = await getGameDb();
|
||||||
@@ -79,6 +84,7 @@ export async function POST(req: Request) {
|
|||||||
deadlineOffsetMs: input.deadlineOffsetMs as number | undefined,
|
deadlineOffsetMs: input.deadlineOffsetMs as number | undefined,
|
||||||
originIcao: input.originIcao as string | undefined,
|
originIcao: input.originIcao as string | undefined,
|
||||||
destIcao: input.destIcao as string | undefined,
|
destIcao: input.destIcao as string | undefined,
|
||||||
|
weightKg: input.weightKg as number | undefined,
|
||||||
});
|
});
|
||||||
await inst.db.insert(schema.packages).values(created);
|
await inst.db.insert(schema.packages).values(created);
|
||||||
await persist(inst);
|
await persist(inst);
|
||||||
|
|||||||
+204
-3
@@ -68,10 +68,46 @@ body {
|
|||||||
color: #cbd5e1;
|
color: #cbd5e1;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* v0.9.0 — single-screen 3-pane shell: left Assets / center map / right Jobs & Market */
|
/* ISS-010 (v0.18.0) — Relocate row inside the airport popup (plain HTML, not React). */
|
||||||
|
.popup-relocate {
|
||||||
|
margin-top: 8px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.popup-relocate select {
|
||||||
|
font-size: 12px;
|
||||||
|
padding: 3px 6px;
|
||||||
|
border-radius: 4px;
|
||||||
|
border: 1px solid rgba(148, 163, 184, 0.4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.popup-relocate button {
|
||||||
|
font-size: 12px;
|
||||||
|
padding: 3px 10px;
|
||||||
|
border-radius: 4px;
|
||||||
|
border: 1px solid rgba(148, 163, 184, 0.4);
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.popup-relocate button:disabled {
|
||||||
|
opacity: 0.5;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-testid='airport-popup-relocate-status'] {
|
||||||
|
font-size: 11px;
|
||||||
|
color: #334155;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* v0.9.0 — single-screen 3-pane shell: left Assets / center map / right Jobs & Market.
|
||||||
|
ISS-021 (v0.20.0): left widened to 360px (it now carries the On board section).
|
||||||
|
ISS-046 (v0.27.1): right widened to match left at 360px — total fixed width 720px, map column shrinks by 80px. */
|
||||||
.app-shell {
|
.app-shell {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: 300px minmax(0, 1fr) 320px;
|
grid-template-columns: 360px minmax(0, 1fr) 360px;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -201,6 +237,7 @@ body {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.plane-loc {
|
.plane-loc {
|
||||||
|
min-width: 0;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
text-overflow: ellipsis;
|
text-overflow: ellipsis;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
@@ -265,6 +302,7 @@ body {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.contract-route {
|
.contract-route {
|
||||||
|
min-width: 0;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: #f1f5f9;
|
color: #f1f5f9;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
@@ -284,6 +322,7 @@ body {
|
|||||||
|
|
||||||
.pane-btn {
|
.pane-btn {
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
|
white-space: nowrap;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
padding: 3px 10px;
|
padding: 3px 10px;
|
||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
@@ -324,6 +363,12 @@ body {
|
|||||||
padding: 4px 0;
|
padding: 4px 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ISS-010 (v0.18.0) — the Relocate row carries TWO selects, so let it wrap instead of
|
||||||
|
squeezing both below their readable width in the 360 px left pane (moved there in ISS-023 v0.21.0). */
|
||||||
|
.market-row-relocate {
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
.market-preview {
|
.market-preview {
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
color: #f8fafc;
|
color: #f8fafc;
|
||||||
@@ -331,7 +376,7 @@ body {
|
|||||||
font-variant-numeric: tabular-nums;
|
font-variant-numeric: tabular-nums;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* v0.12.0 — on-board blocks (per plane) in the right pane */
|
/* v0.12.0 — on-board blocks (per plane); moved to the left pane in ISS-021 (v0.20.0) */
|
||||||
.onboard-block {
|
.onboard-block {
|
||||||
background: rgba(30, 41, 59, 0.6);
|
background: rgba(30, 41, 59, 0.6);
|
||||||
border-radius: 6px;
|
border-radius: 6px;
|
||||||
@@ -339,8 +384,164 @@ body {
|
|||||||
margin-bottom: 8px;
|
margin-bottom: 8px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ISS-028 (v0.20.0 part 2) — on-board cargo rows are two lines: a full-width fly-to button,
|
||||||
|
then refuel + abandon side by side below it; long destination names truncate with an ellipsis. */
|
||||||
.onboard-block .contract-row {
|
.onboard-block .contract-row {
|
||||||
background: transparent;
|
background: transparent;
|
||||||
padding: 6px 0 0;
|
padding: 6px 0 0;
|
||||||
border-top: 1px solid rgba(148, 163, 184, 0.2);
|
border-top: 1px solid rgba(148, 163, 184, 0.2);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.onboard-block .contract-row .contract-sub {
|
||||||
|
margin-top: 0; /* row spacing comes from the container's gap */
|
||||||
|
}
|
||||||
|
|
||||||
|
.onboard-fly-btn {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.onboard-fly-label {
|
||||||
|
display: block;
|
||||||
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.onboard-actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ISS-043 (v0.26.0) — flight-queue sub-section inside on-board blocks */
|
||||||
|
.queue-subsection {
|
||||||
|
margin-top: 8px;
|
||||||
|
padding-top: 6px;
|
||||||
|
border-top: 1px solid rgba(148, 163, 184, 0.2);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.queue-heading {
|
||||||
|
font-size: 11px;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.05em;
|
||||||
|
color: #94a3b8;
|
||||||
|
}
|
||||||
|
|
||||||
|
.queue-row {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* v0.17.0 — ISS-008: bottom-right toast stack (action errors + game events) */
|
||||||
|
.toasts {
|
||||||
|
position: fixed;
|
||||||
|
bottom: 12px;
|
||||||
|
/* 360px right pane + 12px inset — sits flush against the map's right edge, clear of the right pane */
|
||||||
|
right: 372px;
|
||||||
|
z-index: 50; /* above map popups/controls and the app header */
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
max-width: 340px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 8px 12px;
|
||||||
|
border-radius: 6px;
|
||||||
|
font-size: 13px;
|
||||||
|
background: rgba(15, 23, 42, 0.95);
|
||||||
|
color: #e2e8f0;
|
||||||
|
border: 1px solid rgba(148, 163, 184, 0.4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast-error {
|
||||||
|
border-color: rgba(239, 68, 68, 0.7);
|
||||||
|
color: #fecaca;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast-info {
|
||||||
|
border-color: rgba(148, 163, 184, 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast-close {
|
||||||
|
flex-shrink: 0;
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 1;
|
||||||
|
padding: 2px 6px;
|
||||||
|
border-radius: 4px;
|
||||||
|
border: none;
|
||||||
|
background: transparent;
|
||||||
|
color: #94a3b8;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast-close:hover {
|
||||||
|
color: #e2e8f0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ISS-008 — the Time section's notifications opt-in button (same look as .time-controls buttons) */
|
||||||
|
.notif-toggle {
|
||||||
|
margin-top: 8px;
|
||||||
|
font-size: 12px;
|
||||||
|
padding: 4px 10px;
|
||||||
|
border-radius: 4px;
|
||||||
|
border: 1px solid rgba(148, 163, 184, 0.4);
|
||||||
|
background: rgba(30, 41, 59, 0.9);
|
||||||
|
color: #e2e8f0;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.notif-toggle:disabled {
|
||||||
|
opacity: 0.5;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* v0.28.0 (ISS-047) — right pane tabs (Jobs / Planes market) + per-type tech-spec cards */
|
||||||
|
.pane-tabs {
|
||||||
|
display: flex;
|
||||||
|
gap: 6px;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab-btn {
|
||||||
|
flex: 1;
|
||||||
|
font-size: 12px;
|
||||||
|
padding: 4px 8px;
|
||||||
|
border-radius: 4px;
|
||||||
|
border: 1px solid rgba(148, 163, 184, 0.4);
|
||||||
|
background: rgba(30, 41, 59, 0.9);
|
||||||
|
color: #e2e8f0;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab-btn[aria-selected='true'] {
|
||||||
|
background: rgba(56, 189, 248, 0.25);
|
||||||
|
border-color: rgba(56, 189, 248, 0.7);
|
||||||
|
color: #f8fafc;
|
||||||
|
}
|
||||||
|
|
||||||
|
.plane-type-card {
|
||||||
|
background: rgba(30, 41, 59, 0.6);
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 8px;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.plane-type-name {
|
||||||
|
margin: 0 0 6px;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: #f1f5f9;
|
||||||
}
|
}
|
||||||
|
|||||||
+32
-5
@@ -1,11 +1,14 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import dynamic from 'next/dynamic';
|
import dynamic from 'next/dynamic';
|
||||||
import { useState } from 'react';
|
import { useEffect, useRef, useState } from 'react';
|
||||||
import LeftPane from '@/components/LeftPane';
|
import LeftPane from '@/components/LeftPane';
|
||||||
import RightPane from '@/components/RightPane';
|
import RightPane from '@/components/RightPane';
|
||||||
|
import ToastStack from '@/components/Toasts';
|
||||||
import type { HoverTarget } from '@/components/hoverTypes';
|
import type { HoverTarget } from '@/components/hoverTypes';
|
||||||
import { useGameState } from '@/lib/useGameState';
|
import { useGameState } from '@/lib/useGameState';
|
||||||
|
import { useToasts } from '@/lib/useToasts';
|
||||||
|
import { diffSnapshots } from '@/lib/deriveEvents';
|
||||||
|
|
||||||
const Map = dynamic(() => import('@/components/Map'), { ssr: false });
|
const Map = dynamic(() => import('@/components/Map'), { ssr: false });
|
||||||
|
|
||||||
@@ -19,12 +22,36 @@ export default function Home() {
|
|||||||
// either pane highlights the matching plane/route/airports on the map.
|
// either pane highlights the matching plane/route/airports on the map.
|
||||||
const [hovered, setHovered] = useState<HoverTarget | null>(null);
|
const [hovered, setHovered] = useState<HoverTarget | null>(null);
|
||||||
|
|
||||||
|
// ISS-008 (v0.17.0): bottom-right toasts — action errors from both panes plus game events
|
||||||
|
// derived by diffing consecutive snapshots (no server event feed exists).
|
||||||
|
const { toasts, push, dismiss } = useToasts();
|
||||||
|
const onError = (message: string) => push('error', message);
|
||||||
|
|
||||||
|
// Diff each new snapshot against the previous one → info toasts. When the window is hidden
|
||||||
|
// and notifications are granted, mirror them as browser notifications too.
|
||||||
|
const prevSnapshotRef = useRef<typeof state>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
if (state === null) return;
|
||||||
|
for (const event of diffSnapshots(prevSnapshotRef.current, state)) {
|
||||||
|
push('info', event.message);
|
||||||
|
if (document.hidden && 'Notification' in window && Notification.permission === 'granted') {
|
||||||
|
new Notification('Flight Ops', { body: event.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
prevSnapshotRef.current = state;
|
||||||
|
}, [state, push]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="app-shell">
|
<div className="app-shell">
|
||||||
<LeftPane state={state} loading={loading} error={error} onRefresh={refresh} onHover={setHovered} />
|
{/* ISS-021 (v0.20.0) — applySnapshot also reaches the left pane: its On board section's
|
||||||
{/* v0.11.0 — the same polled snapshot drives the map's plane markers + route lines */}
|
refuel/fly/abandon actions push their response snapshot into the shared state */}
|
||||||
<Map state={state} hovered={hovered} />
|
<LeftPane state={state} loading={loading} error={error} onRefresh={refresh} applySnapshot={applySnapshot} onHover={setHovered} onError={onError} />
|
||||||
<RightPane state={state} loading={loading} applySnapshot={applySnapshot} onHover={setHovered} />
|
{/* v0.11.0 — the same polled snapshot drives the map's plane markers + route lines;
|
||||||
|
ISS-010 (v0.18.0) — applySnapshot lets the airport popup's Relocate row push its
|
||||||
|
action response into the shared state, exactly like RightPane does */}
|
||||||
|
<Map state={state} hovered={hovered} applySnapshot={applySnapshot} />
|
||||||
|
<RightPane state={state} loading={loading} applySnapshot={applySnapshot} onHover={setHovered} onError={onError} />
|
||||||
|
<ToastStack toasts={toasts} onDismiss={dismiss} />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
+441
-19
@@ -1,10 +1,15 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react';
|
import { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react';
|
||||||
|
import type { GeoJsonFeatureCollection } from '@/lib/airports';
|
||||||
import type { PlaneState, StateSnapshot } from '@/lib/game/state';
|
import type { PlaneState, StateSnapshot } from '@/lib/game/state';
|
||||||
import { PLANE_TYPES } from '@/lib/game/catalog';
|
import { PLANE_TYPES } from '@/lib/game/catalog';
|
||||||
import { formatCash, formatFuel, formatSimClock } from '@/lib/format';
|
import { abandonPenalty } from '@/lib/game/penalty';
|
||||||
|
import { formatCash, formatDeadlineRelative, formatFuel, formatSimClock } from '@/lib/format';
|
||||||
import { TIME_SCALES, scaleToSlider, sliderToScale } from '@/lib/timeScale';
|
import { TIME_SCALES, scaleToSlider, sliderToScale } from '@/lib/timeScale';
|
||||||
|
import { useGameAction } from '@/lib/useGameAction';
|
||||||
|
import { useSimClock } from '@/lib/useSimClock';
|
||||||
|
import { cargoWeightFor } from './RightPane';
|
||||||
import type { HoverTarget } from './hoverTypes';
|
import type { HoverTarget } from './hoverTypes';
|
||||||
|
|
||||||
interface LeftPaneProps {
|
interface LeftPaneProps {
|
||||||
@@ -13,8 +18,13 @@ interface LeftPaneProps {
|
|||||||
error: string | null;
|
error: string | null;
|
||||||
// The shell's single-poll refresh — called after a sim-control POST so the pane updates immediately.
|
// The shell's single-poll refresh — called after a sim-control POST so the pane updates immediately.
|
||||||
onRefresh: () => void;
|
onRefresh: () => void;
|
||||||
|
// ISS-021 (v0.20.0): push the full snapshot returned by an action endpoint into the shared shell
|
||||||
|
// state — needed now that the On board section's refuel/fly/abandon actions live in this pane.
|
||||||
|
applySnapshot: (snapshot: StateSnapshot) => void;
|
||||||
// ISS-002 (v0.15.0): report fleet-row hovers to the shell so the map can highlight the plane.
|
// ISS-002 (v0.15.0): report fleet-row hovers to the shell so the map can highlight the plane.
|
||||||
onHover: (target: HoverTarget | null) => void;
|
onHover: (target: HoverTarget | null) => void;
|
||||||
|
// ISS-008 (v0.17.0): report a failed sim-control POST to the shell as an error toast.
|
||||||
|
onError?: (message: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Discrete ladder slider (v0.9.2, values reworked in v0.14.0): position t ∈ [0,1] → nearest
|
// Discrete ladder slider (v0.9.2, values reworked in v0.14.0): position t ∈ [0,1] → nearest
|
||||||
@@ -29,13 +39,12 @@ function planeLocation(p: PlaneState): string {
|
|||||||
return p.locationName;
|
return p.locationName;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Cargo loadout "n/capacity pkgs" — expired packages still occupy their slot.
|
// Cargo loadout "X.Xt / Y.Yt" (v0.27.0) — used/max payload in tonnes, one decimal;
|
||||||
|
// expired packages still occupy their payload.
|
||||||
function loadoutFor(state: StateSnapshot, p: PlaneState): string {
|
function loadoutFor(state: StateSnapshot, p: PlaneState): string {
|
||||||
const used = state.packages.filter(
|
const used = cargoWeightFor(state, p.id);
|
||||||
(pkg) => pkg.planeId === p.id && (pkg.status === 'loaded' || pkg.status === 'expired'),
|
const maxPayloadKg = state.catalog.find((e) => e.model === p.model)?.maxPayloadKg ?? PLANE_TYPES[p.model]?.maxPayloadKg ?? 0;
|
||||||
).length;
|
return `${(used / 1000).toFixed(1)}t / ${(maxPayloadKg / 1000).toFixed(1)}t`;
|
||||||
const capacity = state.catalog.find((e) => e.model === p.model)?.capacity ?? PLANE_TYPES[p.model]?.capacity ?? 0;
|
|
||||||
return `${used}/${capacity} pkgs`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ISS-001 — an optimistic slider value is cleared exactly when a rendered snapshot CONFIRMS it
|
// ISS-001 — an optimistic slider value is cleared exactly when a rendered snapshot CONFIRMS it
|
||||||
@@ -45,16 +54,92 @@ export function pendingScaleConfirmed(pendingScale: number | null, serverTimeSca
|
|||||||
return pendingScale !== null && serverTimeScale === pendingScale;
|
return pendingScale !== null && serverTimeScale === pendingScale;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function LeftPane({ state, loading, error, onRefresh, onHover }: LeftPaneProps) {
|
// ISS-008 fix (v0.17.0, CI runs #44/#47): bounded retry for POST /api/sim — a commit dropped by
|
||||||
|
// the runner's flaky uplink used to leave the UI optimistic while the server kept the old scale.
|
||||||
|
// Up to maxAttempts tries with delayMs between them; stops early once superseded() flips (a newer
|
||||||
|
// intent arrived and the caller's loop sends it instead). post is idempotent set-semantics, so
|
||||||
|
// re-sending a body whose response was lost cannot double-apply. Pure core — unit-tested in node.
|
||||||
|
export const SIM_POST_MAX_ATTEMPTS = 3;
|
||||||
|
export const SIM_POST_RETRY_DELAY_MS = 500;
|
||||||
|
|
||||||
|
export type SimPostRetryResult =
|
||||||
|
| { ok: true }
|
||||||
|
| { ok: false; reason: 'exhausted'; error: unknown }
|
||||||
|
| { ok: false; reason: 'superseded' };
|
||||||
|
|
||||||
|
export async function retrySimPost(
|
||||||
|
post: () => Promise<void>,
|
||||||
|
superseded: () => boolean,
|
||||||
|
sleep: (ms: number) => Promise<void> = (ms) => new Promise((r) => setTimeout(r, ms)),
|
||||||
|
maxAttempts: number = SIM_POST_MAX_ATTEMPTS,
|
||||||
|
delayMs: number = SIM_POST_RETRY_DELAY_MS,
|
||||||
|
): Promise<SimPostRetryResult> {
|
||||||
|
let lastError: unknown;
|
||||||
|
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
||||||
|
if (superseded()) return { ok: false, reason: 'superseded' }; // a newer intent takes over — don't even send this body
|
||||||
|
try {
|
||||||
|
await post();
|
||||||
|
return { ok: true };
|
||||||
|
} catch (err) {
|
||||||
|
lastError = err;
|
||||||
|
if (superseded()) return { ok: false, reason: 'superseded' }; // a newer intent arrived during the attempt — don't wait out the backoff
|
||||||
|
if (attempt < maxAttempts) await sleep(delayMs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { ok: false, reason: 'exhausted', error: lastError };
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function LeftPane({ state, loading, error, onRefresh, applySnapshot, onHover, onError }: LeftPaneProps) {
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
|
|
||||||
// POST /api/sim, then refetch the full snapshot immediately so the pane reflects the new
|
// ISS-021 (v0.20.0): shared action runner for the On board section (moved here from RightPane).
|
||||||
// controls without waiting for the next poll tick. On failure keep the stale UI — the
|
const { runAction, busy: actionsBusy, actionError } = useGameAction(state, applySnapshot, onError);
|
||||||
// running poll retries on its own and surfaces the error state. A commit that lands while
|
|
||||||
// another POST is in flight is held in a single slot (last intent wins) and flushed by the
|
// ISS-023 (v0.21.0): Relocate selections — moved here from the right-pane market row; same
|
||||||
// in-flight call, so every user intent reaches the server (the [1,1000] clamp stays as backstop).
|
// "effective selection" pattern as there: the user's pick while it stays valid, else a sensible
|
||||||
// The gate is a REF, not React state: closures never see a stale "busy" value, which used to
|
// default (first grounded plane / first airport).
|
||||||
// let a flush re-queue instead of send and silently drop a commit.
|
const [relocatePlaneId, setRelocatePlaneId] = useState<string | null>(null);
|
||||||
|
const [relocateDestIcao, setRelocateDestIcao] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// ISS-035 (v0.23.0): Refuel-to-full selection — moved here from the right-pane market row; same
|
||||||
|
// "effective selection" pattern as Relocate above: the user's pick while it stays refuelable, else
|
||||||
|
// a sensible default (first grounded plane with fuel below max).
|
||||||
|
const [refuelPlaneId, setRefuelPlaneId] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// ISS-043 (v0.26.0): flight-queue "add" destination — one shared pick across every on-board
|
||||||
|
// block's queue-add select (the e2e fleet is a single plane; per-block state would be dead weight).
|
||||||
|
const [queueAddDestIcao, setQueueAddDestIcao] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// ISS-010 (v0.18.0): one-time /api/airports fetch per page life — destination options for the
|
||||||
|
// Relocate section, sorted by name so e2e selection is stable. Same promise-ref pattern as Map.tsx;
|
||||||
|
// on failure airportOptions stays null and the Relocate button simply remains disabled. Moved here
|
||||||
|
// from RightPane in ISS-023 (v0.21.0) — the relocate-dest select was its only consumer there.
|
||||||
|
const [airportOptions, setAirportOptions] = useState<Array<{ name: string; icao: string }> | null>(null);
|
||||||
|
const airportsPromiseRef = useRef<Promise<Array<{ name: string; icao: string }>> | null>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!airportsPromiseRef.current) {
|
||||||
|
airportsPromiseRef.current = fetch('/api/airports', { cache: 'no-store' })
|
||||||
|
.then((res) => {
|
||||||
|
if (!res.ok) throw new Error(`GET /api/airports → HTTP ${res.status}`);
|
||||||
|
return res.json() as Promise<GeoJsonFeatureCollection>;
|
||||||
|
})
|
||||||
|
.then((fc) =>
|
||||||
|
fc.features
|
||||||
|
.map((f) => ({ name: f.properties.name, icao: f.properties.icao }))
|
||||||
|
.sort((a, b) => a.name.localeCompare(b.name, 'en')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
void airportsPromiseRef.current.then(setAirportOptions).catch(() => {});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// POST /api/sim (retried up to SIM_POST_MAX_ATTEMPTS× on failure — CI runs #44/#47), then
|
||||||
|
// refetch the full snapshot immediately so the pane reflects the new controls without waiting
|
||||||
|
// for the next poll tick. After the final attempt fails keep the stale UI and surface an error
|
||||||
|
// toast (the running poll retries on its own). A commit that lands while another POST is in
|
||||||
|
// flight — including mid-retry — is held in a single slot (last intent wins) and supersedes
|
||||||
|
// the in-flight body, so every user intent reaches the server (the [1,1000] clamp stays as
|
||||||
|
// backstop). The gate is a REF, not React state: closures never see a stale "busy" value,
|
||||||
|
// which used to let a flush re-queue instead of send and silently drop a commit.
|
||||||
const queuedRef = useRef<{ timeScale?: number; paused?: boolean } | null>(null);
|
const queuedRef = useRef<{ timeScale?: number; paused?: boolean } | null>(null);
|
||||||
const busyRef = useRef(false);
|
const busyRef = useRef(false);
|
||||||
|
|
||||||
@@ -75,20 +160,32 @@ export default function LeftPane({ state, loading, error, onRefresh, onHover }:
|
|||||||
try {
|
try {
|
||||||
let current: { timeScale?: number; paused?: boolean } | null = body;
|
let current: { timeScale?: number; paused?: boolean } | null = body;
|
||||||
while (current !== null) {
|
while (current !== null) {
|
||||||
|
const target = current; // stable across this retry round
|
||||||
|
const result = await retrySimPost(
|
||||||
|
async () => {
|
||||||
const res = await fetch('/api/sim', {
|
const res = await fetch('/api/sim', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify(current),
|
body: JSON.stringify(target),
|
||||||
cache: 'no-store',
|
cache: 'no-store',
|
||||||
});
|
});
|
||||||
if (!res.ok) throw new Error(`POST /api/sim → HTTP ${res.status}`);
|
if (!res.ok) throw new Error(`POST /api/sim → HTTP ${res.status}`);
|
||||||
|
},
|
||||||
|
() => queuedRef.current !== null, // a newer intent supersedes the in-flight body mid-retry
|
||||||
|
);
|
||||||
|
if (result.ok) {
|
||||||
onRefresh();
|
onRefresh();
|
||||||
if (current === body) sentOwn = true; // object identity — queued bodies are fresh literals
|
if (target === body) sentOwn = true; // object identity — queued bodies are fresh literals
|
||||||
|
} else if (result.reason === 'exhausted') {
|
||||||
|
throw result.error; // only after the final attempt fails → error toast below
|
||||||
|
}
|
||||||
current = queuedRef.current; // pick up anything that arrived while we were in flight
|
current = queuedRef.current; // pick up anything that arrived while we were in flight
|
||||||
queuedRef.current = null;
|
queuedRef.current = null;
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('failed to apply sim controls', err);
|
console.error('failed to apply sim controls', err);
|
||||||
|
// ISS-008: surface the failure as an error toast too — previously console-only.
|
||||||
|
onError?.(`Failed to update time controls (${err instanceof Error ? err.message : String(err)})`);
|
||||||
queuedRef.current = null; // don't replay a stale intent after a failed round-trip
|
queuedRef.current = null; // don't replay a stale intent after a failed round-trip
|
||||||
} finally {
|
} finally {
|
||||||
busyRef.current = false;
|
busyRef.current = false;
|
||||||
@@ -96,12 +193,40 @@ export default function LeftPane({ state, loading, error, onRefresh, onHover }:
|
|||||||
}
|
}
|
||||||
return sentOwn ? 'sent' : 'failed';
|
return sentOwn ? 'sent' : 'failed';
|
||||||
},
|
},
|
||||||
[onRefresh],
|
[onRefresh, onError],
|
||||||
);
|
);
|
||||||
|
|
||||||
const paused = state?.simState.paused ?? false;
|
const paused = state?.simState.paused ?? false;
|
||||||
const timeScale = state?.simState.timeScale ?? 1;
|
const timeScale = state?.simState.timeScale ?? 1;
|
||||||
|
|
||||||
|
// On board (v0.12.0, moved from the right pane in ISS-021 v0.20.0): every plane that carries
|
||||||
|
// cargo or is mid-flight gets a block — its loaded/expired packages with fly-to-destination +
|
||||||
|
// abandon controls, and flying planes show their current leg.
|
||||||
|
const clockMs = state?.simState.clockMs ?? 0;
|
||||||
|
// ISS-043 (v0.26.0): a plane with queued legs always shows its block too — the queue is the
|
||||||
|
// reason it's here even when grounded with nothing on board.
|
||||||
|
const onboard = state
|
||||||
|
? state.planes.filter((p) => p.status === 'flying' || cargoWeightFor(state, p.id) > 0 || (p.queue?.length ?? 0) > 0)
|
||||||
|
: [];
|
||||||
|
|
||||||
|
// ISS-023 (v0.21.0): Relocate — any GROUNDED plane can be repositioned to any airport via the
|
||||||
|
// existing fly endpoint (pure repositioning, no package needed since v0.12.0). Moved here from
|
||||||
|
// the right-pane market row; with state null both fall back to null and the section isn't rendered.
|
||||||
|
const grounded = state ? state.planes.filter((p) => p.status === 'available') : [];
|
||||||
|
const relocatePlane = grounded.find((p) => p.id === relocatePlaneId) ?? grounded[0] ?? null;
|
||||||
|
const relocateDest =
|
||||||
|
airportOptions === null ? null : airportOptions.find((a) => a.icao === relocateDestIcao) ?? airportOptions[0] ?? null;
|
||||||
|
|
||||||
|
// ISS-035 (v0.23.0): Refuel-to-full — any GROUNDED plane with fuel below max can be topped up via the
|
||||||
|
// existing refuel endpoint (no body → server defaults to mode 'full'). Moved here from the right-pane
|
||||||
|
// market row; reuses `grounded` above, and with state null falls back to null.
|
||||||
|
const refuelable = grounded.filter((p) => p.fuel < p.maxFuel);
|
||||||
|
const refuelPlane =
|
||||||
|
(state?.planes.find((p) => p.id === refuelPlaneId && p.status === 'available' && p.fuel < p.maxFuel)) ??
|
||||||
|
refuelable[0] ??
|
||||||
|
null;
|
||||||
|
const refuelCost = refuelPlane && state ? (refuelPlane.maxFuel - refuelPlane.fuel) * state.fuelPricePerL : null;
|
||||||
|
|
||||||
// Slider commit (v0.9.1): the displayed value follows the drag optimistically via
|
// Slider commit (v0.9.1): the displayed value follows the drag optimistically via
|
||||||
// pendingScale; POST /api/sim fires after a 250 ms debounce, or immediately when the
|
// pendingScale; POST /api/sim fires after a 250 ms debounce, or immediately when the
|
||||||
// user releases the slider (browsers fire a native 'change' on release). The server's
|
// user releases the slider (browsers fire a native 'change' on release). The server's
|
||||||
@@ -165,8 +290,33 @@ export default function LeftPane({ state, loading, error, onRefresh, onHover }:
|
|||||||
[],
|
[],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// ISS-008: browser-notification opt-in. Starts null (SSR-safe — the real permission is read
|
||||||
|
// in an effect after hydration, so server and client render identically) and follows the
|
||||||
|
// result of Notification.requestPermission(). 'unsupported' = no Notification API at all.
|
||||||
|
const [notifPermission, setNotifPermission] = useState<string | null>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
if ('Notification' in window) setNotifPermission(Notification.permission);
|
||||||
|
else setNotifPermission('unsupported');
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// null (pre-effect) and 'default' both read as the opt-in prompt.
|
||||||
|
const notifLabel: string =
|
||||||
|
notifPermission === 'granted'
|
||||||
|
? 'Notifications enabled'
|
||||||
|
: notifPermission === 'denied'
|
||||||
|
? 'Notifications blocked'
|
||||||
|
: notifPermission === 'unsupported'
|
||||||
|
? 'Notifications unavailable'
|
||||||
|
: 'Enable notifications';
|
||||||
|
|
||||||
const displayedScale = pendingScale ?? timeScale;
|
const displayedScale = pendingScale ?? timeScale;
|
||||||
|
|
||||||
|
// ISS-007: the clock ticks client-side between polls, re-syncing to server truth on every
|
||||||
|
// snapshot. Fed with EFFECTIVE controls so a scale drag / pause click takes effect immediately,
|
||||||
|
// not when the confirming snapshot lands. Only the sim-clock paragraph uses this — deadline and
|
||||||
|
// penalty previews stay snapshot-based (deterministic against the server clock).
|
||||||
|
const simClockMs = useSimClock(state, { timeScale: displayedScale, paused });
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<aside data-testid="left-pane" className="pane left-pane">
|
<aside data-testid="left-pane" className="pane left-pane">
|
||||||
<h2 className="pane-title">Assets</h2>
|
<h2 className="pane-title">Assets</h2>
|
||||||
@@ -218,10 +368,262 @@ export default function LeftPane({ state, loading, error, onRefresh, onHover }:
|
|||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
{/* ISS-021 (v0.20.0): moved here from the right pane — between Fleet and Time. */}
|
||||||
|
<section className="pane-section">
|
||||||
|
<h3 className="pane-heading">On board</h3>
|
||||||
|
{onboard.length === 0 ? (
|
||||||
|
<p className="pane-muted">Nothing on board.</p>
|
||||||
|
) : (
|
||||||
|
onboard.map((plane) => {
|
||||||
|
const cargo = state.packages.filter(
|
||||||
|
(pkg) => pkg.planeId === plane.id && (pkg.status === 'loaded' || pkg.status === 'expired'),
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
// ISS-002: hovering the on-board block (including its cargo rows) highlights the plane.
|
||||||
|
// Handlers live only on the outer div — React's enter/leave don't fire when moving to a
|
||||||
|
// child, so this covers the whole block without flicker between sub-elements.
|
||||||
|
<div
|
||||||
|
key={plane.id}
|
||||||
|
data-testid={`onboard-${plane.id}`}
|
||||||
|
className="onboard-block"
|
||||||
|
onMouseEnter={() => onHover({ kind: 'plane', id: plane.id })}
|
||||||
|
onMouseLeave={() => onHover(null)}
|
||||||
|
>
|
||||||
|
<div className="contract-main">
|
||||||
|
<span className="plane-model">{PLANE_TYPES[plane.model]?.name ?? plane.model}</span>
|
||||||
|
{plane.status === 'flying' ? (
|
||||||
|
<>
|
||||||
|
<span className="plane-status status-flying">in flight</span>
|
||||||
|
{plane.destName && (
|
||||||
|
<span data-testid={`plane-leg-${plane.id}`} className="contract-route">
|
||||||
|
{plane.locationName} → {plane.destName}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<span className="plane-status status-available">{plane.locationIcao}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{cargo.map((pkg) => {
|
||||||
|
const penalty = abandonPenalty(pkg, clockMs);
|
||||||
|
return (
|
||||||
|
// ISS-025 (v0.22.0): hovering a loaded package draws its full origin→dest trace on the map —
|
||||||
|
// same as job-list rows — and keeps this plane's halo lit via planeId. Leaving the row restores
|
||||||
|
// the block's plain plane highlight; leaving the whole block still ends at null (the child's
|
||||||
|
// mouseleave fires before the parent's).
|
||||||
|
<div
|
||||||
|
key={pkg.id}
|
||||||
|
data-testid={`onboard-package-${pkg.id}`}
|
||||||
|
className="contract-row"
|
||||||
|
onMouseEnter={() => onHover({ kind: 'package', originIcao: pkg.originIcao, destIcao: pkg.destIcao, planeId: plane.id })}
|
||||||
|
onMouseLeave={() => onHover({ kind: 'plane', id: plane.id })}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid={`fly-to-${pkg.id}`}
|
||||||
|
className="pane-btn onboard-fly-btn"
|
||||||
|
disabled={actionsBusy || plane.status !== 'available'}
|
||||||
|
onClick={() => void runAction(`/api/planes/${plane.id}/fly`, { destIcao: pkg.destIcao })}
|
||||||
|
>
|
||||||
|
<span className="onboard-fly-label" title={`Fly to ${pkg.destName}`}>
|
||||||
|
Fly to {pkg.destName}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
<div className="onboard-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid={`refuel-for-${pkg.id}`}
|
||||||
|
className="pane-btn"
|
||||||
|
disabled={actionsBusy || plane.status !== 'available'}
|
||||||
|
onClick={() => void runAction(`/api/planes/${plane.id}/refuel`, { mode: 'forFlight', packageId: pkg.id })}
|
||||||
|
>
|
||||||
|
Refuel
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid={`abandon-${pkg.id}`}
|
||||||
|
className="pane-btn"
|
||||||
|
disabled={actionsBusy || plane.status !== 'available'}
|
||||||
|
onClick={() => void runAction(`/api/packages/${pkg.id}/abandon`)}
|
||||||
|
>
|
||||||
|
Abandon{' '}
|
||||||
|
<span data-testid={`abandon-penalty-${pkg.id}`}>−{formatCash(penalty)}</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="contract-sub">
|
||||||
|
<span className="contract-route">{pkg.originName} → {pkg.destName}</span>
|
||||||
|
<span>{formatCash(pkg.reward)}</span>
|
||||||
|
{pkg.status === 'expired' ? (
|
||||||
|
<span data-testid={`onboard-expired-${pkg.id}`}>expired</span>
|
||||||
|
) : (
|
||||||
|
<span>{formatDeadlineRelative(pkg.deadlineSimTime, clockMs)}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
{/* ISS-043 (v0.26.0): flight queue — the not-yet-started legs with cancel, plus an
|
||||||
|
add control reusing this pane's already-fetched airport options (no second fetch). */}
|
||||||
|
<div className="queue-subsection">
|
||||||
|
<span className="queue-heading">Queue</span>
|
||||||
|
{plane.queue.map((icao, i) => (
|
||||||
|
<div key={`${icao}-${i}`} data-testid={`queue-leg-${i}`} className="queue-row">
|
||||||
|
<span className="contract-route">
|
||||||
|
{airportOptions?.find((a) => a.icao === icao)?.name ?? icao} ({icao})
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid={`queue-cancel-${i}`}
|
||||||
|
className="pane-btn"
|
||||||
|
disabled={actionsBusy}
|
||||||
|
onClick={() => void runAction(`/api/planes/${plane.id}/queue/cancel`, { index: i })}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<div className="market-row">
|
||||||
|
<select
|
||||||
|
data-testid="queue-add-dest"
|
||||||
|
aria-label="Airport to add to the flight queue"
|
||||||
|
value={queueAddDestIcao ?? ''}
|
||||||
|
onChange={(e) => setQueueAddDestIcao(e.target.value || null)}
|
||||||
|
>
|
||||||
|
<option value="">Select an airport…</option>
|
||||||
|
{airportOptions?.map((a) => (
|
||||||
|
<option key={a.icao} value={a.icao}>
|
||||||
|
{a.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid="queue-add"
|
||||||
|
className="pane-btn"
|
||||||
|
disabled={actionsBusy || queueAddDestIcao === null}
|
||||||
|
onClick={() => {
|
||||||
|
if (queueAddDestIcao) void runAction(`/api/planes/${plane.id}/queue`, { destIcao: queueAddDestIcao });
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Add to queue
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* ISS-023 (v0.21.0): moved here from the right-pane market row — it belongs with
|
||||||
|
everything else about our planes, between On board and Time. */}
|
||||||
|
{/* ISS-027 (v0.22.0): hovering the section previews the planned relocation on the map —
|
||||||
|
dashed trace from the selected plane's airport to the destination + a ring on the target.
|
||||||
|
With no grounded plane or no loaded airport options there is nothing to preview → null. */}
|
||||||
|
<section
|
||||||
|
className="pane-section"
|
||||||
|
data-testid="relocate-section"
|
||||||
|
onMouseEnter={() =>
|
||||||
|
onHover(
|
||||||
|
relocatePlane && relocateDest
|
||||||
|
? { kind: 'route', fromIcao: relocatePlane.locationIcao, toIcao: relocateDest.icao }
|
||||||
|
: null,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
onMouseLeave={() => onHover(null)}
|
||||||
|
>
|
||||||
|
<h3 className="pane-heading">Relocate</h3>
|
||||||
|
{/* ISS-010 (v0.18.0): relocate a grounded plane — the fly endpoint already allows pure
|
||||||
|
repositioning, this row just exposes it for planes with nothing on board. */}
|
||||||
|
<div className="market-row market-row-relocate">
|
||||||
|
<select
|
||||||
|
data-testid="relocate-plane"
|
||||||
|
aria-label="Plane to relocate"
|
||||||
|
value={relocatePlane?.id ?? ''}
|
||||||
|
onChange={(e) => setRelocatePlaneId(e.target.value || null)}
|
||||||
|
>
|
||||||
|
{grounded.map((p) => (
|
||||||
|
<option key={p.id} value={p.id}>
|
||||||
|
{PLANE_TYPES[p.model]?.name ?? p.model} — {p.locationIcao}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<select
|
||||||
|
data-testid="relocate-dest"
|
||||||
|
aria-label="Relocation destination airport"
|
||||||
|
value={relocateDest?.icao ?? ''}
|
||||||
|
onChange={(e) => setRelocateDestIcao(e.target.value || null)}
|
||||||
|
>
|
||||||
|
{airportOptions?.map((a) => (
|
||||||
|
<option key={a.icao} value={a.icao}>
|
||||||
|
{a.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid="relocate-go"
|
||||||
|
className="pane-btn"
|
||||||
|
disabled={actionsBusy || relocatePlane === null || relocateDest === null}
|
||||||
|
onClick={() => {
|
||||||
|
if (relocatePlane && relocateDest) {
|
||||||
|
void runAction(`/api/planes/${relocatePlane.id}/fly`, { destIcao: relocateDest.icao });
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Relocate
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* ISS-035 (v0.23.0): moved here from the right-pane market row — it belongs with everything else
|
||||||
|
about our planes, next to Relocate. Plain section: no hover handlers (refuel is not a route). */}
|
||||||
|
<section className="pane-section" data-testid="refuel-section">
|
||||||
|
<h3 className="pane-heading">Refuel</h3>
|
||||||
|
{/* Moved verbatim from the right-pane Market section — same testids/labels; the per-package
|
||||||
|
"Refuel" button in On board (mode 'forFlight') is a different feature and stays there. */}
|
||||||
|
<div className="market-row">
|
||||||
|
{refuelable.length === 0 ? (
|
||||||
|
<span data-testid="market-refuel-none" className="pane-muted">
|
||||||
|
All tanks full.
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<select
|
||||||
|
data-testid="market-refuel-plane"
|
||||||
|
aria-label="Plane to refuel"
|
||||||
|
value={refuelPlane?.id ?? ''}
|
||||||
|
onChange={(e) => setRefuelPlaneId(e.target.value || null)}
|
||||||
|
>
|
||||||
|
{refuelable.map((p) => (
|
||||||
|
<option key={p.id} value={p.id}>
|
||||||
|
{PLANE_TYPES[p.model]?.name ?? p.model} — {Math.round(p.fuel)} / {p.maxFuel} L
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<span data-testid="market-refuel-cost" className="market-preview">
|
||||||
|
{refuelCost !== null ? formatCash(refuelCost) : ''}
|
||||||
|
</span>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid="market-refuel"
|
||||||
|
className="pane-btn"
|
||||||
|
disabled={actionsBusy || refuelPlane === null}
|
||||||
|
onClick={() => {
|
||||||
|
if (refuelPlane) void runAction(`/api/planes/${refuelPlane.id}/refuel`);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Refuel to full
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<section className="pane-section">
|
<section className="pane-section">
|
||||||
<h3 className="pane-heading">Time</h3>
|
<h3 className="pane-heading">Time</h3>
|
||||||
<p data-testid="sim-clock" className="sim-clock">
|
<p data-testid="sim-clock" className="sim-clock">
|
||||||
{formatSimClock(state.simState.clockMs)}
|
{simClockMs !== null && formatSimClock(simClockMs)}
|
||||||
{paused ? ' (paused)' : ''}
|
{paused ? ' (paused)' : ''}
|
||||||
</p>
|
</p>
|
||||||
<div className="time-controls">
|
<div className="time-controls">
|
||||||
@@ -246,6 +648,24 @@ export default function LeftPane({ state, loading, error, onRefresh, onHover }:
|
|||||||
/>
|
/>
|
||||||
<span data-testid="time-scale-value">{displayedScale}×</span>
|
<span data-testid="time-scale-value">{displayedScale}×</span>
|
||||||
</div>
|
</div>
|
||||||
|
{/* ISS-008: explicit opt-in for browser notifications (fired when the window is hidden). */}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid="enable-notifications"
|
||||||
|
className="notif-toggle"
|
||||||
|
disabled={notifPermission === 'unsupported'}
|
||||||
|
title={notifPermission === 'unsupported' ? 'This browser does not support notifications' : undefined}
|
||||||
|
onClick={() => {
|
||||||
|
// A rejection (rare — e.g. some headless setups) reads as "blocked".
|
||||||
|
if ('Notification' in window) {
|
||||||
|
void Notification.requestPermission()
|
||||||
|
.then(setNotifPermission)
|
||||||
|
.catch(() => setNotifPermission('denied'));
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{notifLabel}
|
||||||
|
</button>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
{error && (
|
{error && (
|
||||||
@@ -253,6 +673,8 @@ export default function LeftPane({ state, loading, error, onRefresh, onHover }:
|
|||||||
{error}
|
{error}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
|
{/* ISS-021 (v0.20.0): inline error from a failed On board action — mirrors right-error. */}
|
||||||
|
{actionError && <p data-testid="left-action-error" className="pane-error">{actionError}</p>}
|
||||||
</>
|
</>
|
||||||
) : null}
|
) : null}
|
||||||
</aside>
|
</aside>
|
||||||
|
|||||||
+183
-11
@@ -8,7 +8,7 @@ import { DEFAULT_STYLE_ID, STYLES, STYLE_STORAGE_KEY, isStyleId, localAssetsAvai
|
|||||||
import type { GeoJsonFeatureCollection } from '../lib/airports';
|
import type { GeoJsonFeatureCollection } from '../lib/airports';
|
||||||
import type { StateSnapshot } from '../lib/game/state';
|
import type { StateSnapshot } from '../lib/game/state';
|
||||||
import type { HoverTarget } from './hoverTypes';
|
import type { HoverTarget } from './hoverTypes';
|
||||||
import { planesGeoJson, routesGeoJson, type AirportCoord, type PlaneFeatureProps } from '../lib/mapData';
|
import { hoverRouteGeoJson, hoverTraceGeoJson, planesGeoJson, queuedRoutesGeoJson, routesGeoJson, type AirportCoord, type PlaneFeatureProps } from '../lib/mapData';
|
||||||
import { weatherFor } from '../lib/weather';
|
import { weatherFor } from '../lib/weather';
|
||||||
import { approxLocalTime } from '../lib/localTime';
|
import { approxLocalTime } from '../lib/localTime';
|
||||||
|
|
||||||
@@ -28,11 +28,24 @@ const PLANES_GROUNDED_LAYER_ID = 'planes-grounded';
|
|||||||
const PLANES_FLYING_LAYER_ID = 'planes-flying';
|
const PLANES_FLYING_LAYER_ID = 'planes-flying';
|
||||||
const ROUTES_SOURCE_ID = 'routes';
|
const ROUTES_SOURCE_ID = 'routes';
|
||||||
const ROUTES_LEGS_LAYER_ID = 'routes-legs';
|
const ROUTES_LEGS_LAYER_ID = 'routes-legs';
|
||||||
|
// ISS-043 (v0.26.0): the dotted queue line — a flying plane's NOT-yet-started legs
|
||||||
|
// (dest → queue[0] → …) as their own source + layer, drawn under everything else dynamic.
|
||||||
|
const QUEUE_ROUTES_SOURCE_ID = 'queue-routes';
|
||||||
|
const QUEUE_ROUTES_LAYER_ID = 'queue-routes';
|
||||||
// ISS-002 (v0.15.0): top-most hover-highlight layers, added after the base layers so they
|
// ISS-002 (v0.15.0): top-most hover-highlight layers, added after the base layers so they
|
||||||
// render above them. Each starts filtered to match nothing; applyHoverRef drives the filters.
|
// render above them. Each starts filtered to match nothing; applyHoverRef drives the filters.
|
||||||
const PLANES_HIGHLIGHT_LAYER_ID = 'planes-highlight';
|
const PLANES_HIGHLIGHT_LAYER_ID = 'planes-highlight';
|
||||||
const ROUTES_HIGHLIGHT_LAYER_ID = 'routes-highlight';
|
const ROUTES_HIGHLIGHT_LAYER_ID = 'routes-highlight';
|
||||||
const AIRPORTS_HIGHLIGHT_LAYER_ID = 'airports-highlight';
|
const AIRPORTS_HIGHLIGHT_LAYER_ID = 'airports-highlight';
|
||||||
|
// ISS-022/025/027 (v0.22.0): the hover route trace — its OWN source + top-most dashed line,
|
||||||
|
// because the shared `routes` source only holds FLYING legs: an open package's or a grounded
|
||||||
|
// relocation's planned route is never in it. applyHoverRef pushes data into it on every hover.
|
||||||
|
const HOVER_ROUTES_SOURCE_ID = 'hover-routes';
|
||||||
|
const HOVER_ROUTE_LAYER_ID = 'hover-route';
|
||||||
|
// ISS-022 (v0.22.0): the DESTINATION airport's ring — a second, differently-colored circle over
|
||||||
|
// the same `airports` source so the target stands out from the origin's plain yellow ring.
|
||||||
|
// applyHoverRef filters it to the hovered target's destination icao only.
|
||||||
|
const AIRPORTS_TARGET_HIGHLIGHT_LAYER_ID = 'airports-target-highlight';
|
||||||
|
|
||||||
function escapeHtml(s: string): string {
|
function escapeHtml(s: string): string {
|
||||||
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||||
@@ -43,13 +56,17 @@ interface MapProps {
|
|||||||
// route lines. Null until the first successful poll.
|
// route lines. Null until the first successful poll.
|
||||||
state?: StateSnapshot | null;
|
state?: StateSnapshot | null;
|
||||||
// ISS-002 (v0.15.0): the side panels' hover target — highlights the matching plane
|
// ISS-002 (v0.15.0): the side panels' hover target — highlights the matching plane
|
||||||
// (+ its route leg if flying) or a package's endpoint airports. Null = nothing hovered.
|
// (+ its route leg if flying) or a package's endpoint airports, and (ISS-022/025/027 v0.22.0)
|
||||||
|
// draws the full great-circle trace between any hovered target's two endpoints. Null = nothing hovered.
|
||||||
hovered?: HoverTarget | null;
|
hovered?: HoverTarget | null;
|
||||||
|
// ISS-010 (v0.18.0): push an action endpoint's full response snapshot into the shared
|
||||||
|
// shell state — same callback RightPane receives, used by the airport popup's Relocate row.
|
||||||
|
applySnapshot: (snapshot: StateSnapshot) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Named FlightMap (not Map): a component called `Map` would shadow the global
|
// Named FlightMap (not Map): a component called `Map` would shadow the global
|
||||||
// Map constructor inside its own body, breaking `new Map(...)` for the airport index.
|
// Map constructor inside its own body, breaking `new Map(...)` for the airport index.
|
||||||
export default function FlightMap({ state, hovered }: MapProps) {
|
export default function FlightMap({ state, hovered, applySnapshot }: MapProps) {
|
||||||
const containerRef = useRef<HTMLDivElement>(null);
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
const mapRef = useRef<maplibregl.Map | null>(null);
|
const mapRef = useRef<maplibregl.Map | null>(null);
|
||||||
// /api/airports is fetched at most once per page life: every styledata event
|
// /api/airports is fetched at most once per page life: every styledata event
|
||||||
@@ -58,6 +75,12 @@ export default function FlightMap({ state, hovered }: MapProps) {
|
|||||||
// Latest snapshot + airport coordinate index, so the mount effect's styledata wiring
|
// Latest snapshot + airport coordinate index, so the mount effect's styledata wiring
|
||||||
// and the state-change effect can both push data without prop-drilling into closures.
|
// and the state-change effect can both push data without prop-drilling into closures.
|
||||||
const stateRef = useRef<StateSnapshot | null>(null);
|
const stateRef = useRef<StateSnapshot | null>(null);
|
||||||
|
// ISS-010 (v0.18.0): the shell's applySnapshot is stable (useCallback with no deps), but the
|
||||||
|
// mount effect captures it once — keep a ref so the popup wiring always calls the latest one.
|
||||||
|
const applySnapshotRef = useRef(applySnapshot);
|
||||||
|
useEffect(() => {
|
||||||
|
applySnapshotRef.current = applySnapshot;
|
||||||
|
}, [applySnapshot]);
|
||||||
const airportsIndexRef = useRef<Map<string, AirportCoord> | null>(null);
|
const airportsIndexRef = useRef<Map<string, AirportCoord> | null>(null);
|
||||||
const [airportCount, setAirportCount] = useState<number | null>(null);
|
const [airportCount, setAirportCount] = useState<number | null>(null);
|
||||||
const [styleId, setStyleId] = useState<string>(DEFAULT_STYLE_ID);
|
const [styleId, setStyleId] = useState<string>(DEFAULT_STYLE_ID);
|
||||||
@@ -76,11 +99,19 @@ export default function FlightMap({ state, hovered }: MapProps) {
|
|||||||
if (routesSource && airportsIndexRef.current) {
|
if (routesSource && airportsIndexRef.current) {
|
||||||
void routesSource.setData(routesGeoJson(st, airportsIndexRef.current));
|
void routesSource.setData(routesGeoJson(st, airportsIndexRef.current));
|
||||||
}
|
}
|
||||||
|
// ISS-043 (v0.26.0): the dotted queue line — same airport-index guard as the solid legs above.
|
||||||
|
const queueRoutesSource = map.getSource(QUEUE_ROUTES_SOURCE_ID) as maplibregl.GeoJSONSource | undefined;
|
||||||
|
if (queueRoutesSource && airportsIndexRef.current) {
|
||||||
|
void queueRoutesSource.setData(queuedRoutesGeoJson(st.planes, airportsIndexRef.current));
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
stateRef.current = state ?? null;
|
stateRef.current = state ?? null;
|
||||||
applyDynamicRef.current();
|
applyDynamicRef.current();
|
||||||
|
// ISS-040 (v0.23.2): re-apply the hover too, so an on-board package's trace follows a moving
|
||||||
|
// carrier between polls while hovered — idempotent and cheap (one small setData + ring filters).
|
||||||
|
applyHoverRef.current();
|
||||||
}, [state]);
|
}, [state]);
|
||||||
|
|
||||||
// ISS-002 (v0.15.0): hover highlight — same ref + effect pattern as the snapshot above.
|
// ISS-002 (v0.15.0): hover highlight — same ref + effect pattern as the snapshot above.
|
||||||
@@ -92,22 +123,56 @@ export default function FlightMap({ state, hovered }: MapProps) {
|
|||||||
const map = mapRef.current;
|
const map = mapRef.current;
|
||||||
if (!map) return;
|
if (!map) return;
|
||||||
const h = hoveredRef.current;
|
const h = hoveredRef.current;
|
||||||
// The empty-string sentinel matches nothing: no feature has id/icao ''.
|
// The empty-string sentinel matches nothing: no feature has id/icao ''. A package hover may
|
||||||
const planeId = h && h.kind === 'plane' ? h.id : '';
|
// name its plane (ISS-025 on-board cargo rows), so that plane's halo stays lit too.
|
||||||
|
let planeId = '';
|
||||||
|
let fromIcao = '';
|
||||||
|
let toIcao = '';
|
||||||
|
if (h) {
|
||||||
|
if (h.kind === 'plane') planeId = h.id;
|
||||||
|
else if (h.kind === 'package') {
|
||||||
|
planeId = h.planeId ?? '';
|
||||||
|
fromIcao = h.originIcao;
|
||||||
|
toIcao = h.destIcao;
|
||||||
|
} else {
|
||||||
|
// 'route' — the Relocate panel's planned flight: trace + target airport only.
|
||||||
|
fromIcao = h.fromIcao;
|
||||||
|
toIcao = h.toIcao;
|
||||||
|
}
|
||||||
|
}
|
||||||
if (map.getLayer(PLANES_HIGHLIGHT_LAYER_ID)) {
|
if (map.getLayer(PLANES_HIGHLIGHT_LAYER_ID)) {
|
||||||
map.setFilter(PLANES_HIGHLIGHT_LAYER_ID, ['==', ['get', 'id'], planeId]);
|
map.setFilter(PLANES_HIGHLIGHT_LAYER_ID, ['==', ['get', 'id'], planeId]);
|
||||||
}
|
}
|
||||||
if (map.getLayer(ROUTES_HIGHLIGHT_LAYER_ID)) {
|
if (map.getLayer(ROUTES_HIGHLIGHT_LAYER_ID)) {
|
||||||
map.setFilter(ROUTES_HIGHLIGHT_LAYER_ID, ['==', ['get', 'planeId'], planeId]);
|
map.setFilter(ROUTES_HIGHLIGHT_LAYER_ID, ['==', ['get', 'planeId'], planeId]);
|
||||||
}
|
}
|
||||||
const originIcao = h && h.kind === 'package' ? h.originIcao : '';
|
// ISS-022/025/027: the hover route trace — one great-circle line for any target carrying two
|
||||||
const destIcao = h && h.kind === 'package' ? h.destIcao : '';
|
// ICAOs (package origin→dest / relocate fromIcao→toIcao); empty when either endpoint is unknown.
|
||||||
|
const hoverSource = map.getSource(HOVER_ROUTES_SOURCE_ID) as maplibregl.GeoJSONSource | undefined;
|
||||||
|
if (hoverSource) {
|
||||||
|
// ISS-040 (v0.23.2): an on-board package's trace starts from the carrier plane's LIVE position,
|
||||||
|
// not its origin airport — identical to before while grounded at the pickup, different once it
|
||||||
|
// has departed with cargo still loaded. No carrier in state yet → fall back to the ICAO trace.
|
||||||
|
const idx = airportsIndexRef.current ?? new Map();
|
||||||
|
const carrier = h?.kind === 'package' && h.planeId ? stateRef.current?.planes.find((p) => p.id === h.planeId) : undefined;
|
||||||
|
void hoverSource.setData(
|
||||||
|
carrier ? hoverTraceGeoJson({ lat: carrier.lat, lon: carrier.lon }, toIcao, idx) : hoverRouteGeoJson(fromIcao, toIcao, idx),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Package hovers ring BOTH endpoints (v0.15.0 behavior); 'route' hovers ring the TARGET only —
|
||||||
|
// the relocation's destination is what ISS-027 asks to see. Plane hovers ring nothing.
|
||||||
|
const originIcao = h?.kind === 'package' ? fromIcao : '';
|
||||||
|
const destIcao = h?.kind === 'package' || h?.kind === 'route' ? toIcao : '';
|
||||||
if (map.getLayer(AIRPORTS_HIGHLIGHT_LAYER_ID)) {
|
if (map.getLayer(AIRPORTS_HIGHLIGHT_LAYER_ID)) {
|
||||||
map.setFilter(
|
map.setFilter(
|
||||||
AIRPORTS_HIGHLIGHT_LAYER_ID,
|
AIRPORTS_HIGHLIGHT_LAYER_ID,
|
||||||
['any', ['==', ['get', 'icao'], originIcao], ['==', ['get', 'icao'], destIcao]],
|
['any', ['==', ['get', 'icao'], originIcao], ['==', ['get', 'icao'], destIcao]],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
// ISS-022: the destination gets its own distinct-colored ring on top (package AND route hovers).
|
||||||
|
if (map.getLayer(AIRPORTS_TARGET_HIGHLIGHT_LAYER_ID)) {
|
||||||
|
map.setFilter(AIRPORTS_TARGET_HIGHLIGHT_LAYER_ID, ['==', ['get', 'icao'], destIcao]);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -156,16 +221,67 @@ export default function FlightMap({ state, hovered }: MapProps) {
|
|||||||
// deterministic generated weather — no gameplay effects per PLAN.md.
|
// deterministic generated weather — no gameplay effects per PLAN.md.
|
||||||
const w = weatherFor(p.icao);
|
const w = weatherFor(p.icao);
|
||||||
const localTime = approxLocalTime(p.lon, Date.now());
|
const localTime = approxLocalTime(p.lon, Date.now());
|
||||||
new maplibregl.Popup({ offset: 10 })
|
// ISS-010 (v0.18.0): Relocate row — grounded planes from the latest snapshot can be
|
||||||
|
// repositioned to this airport via POST /api/planes/{id}/fly (pure repositioning).
|
||||||
|
const st = stateRef.current;
|
||||||
|
const groundedPlanes = st ? st.planes.filter((pl) => pl.status === 'available') : [];
|
||||||
|
const planeLabel = (model: string) => st?.catalog.find((c) => c.model === model)?.label ?? model;
|
||||||
|
const relocateHtml =
|
||||||
|
groundedPlanes.length > 0
|
||||||
|
? `<select data-testid="airport-popup-plane" aria-label="Plane to relocate here">` +
|
||||||
|
`<option value="">Select a plane\u2026</option>` +
|
||||||
|
groundedPlanes.map(
|
||||||
|
(pl) =>
|
||||||
|
`<option value="${escapeHtml(pl.id)}">${escapeHtml(planeLabel(pl.model))} \u2014 ${escapeHtml(pl.locationIcao)}</option>`,
|
||||||
|
).join('') +
|
||||||
|
`</select><button type="button" data-testid="airport-popup-relocate" disabled>Relocate here</button>`
|
||||||
|
: `<span data-testid="airport-popup-no-planes">No grounded planes to relocate.</span>`;
|
||||||
|
const popup = new maplibregl.Popup({ offset: 10 })
|
||||||
.setLngLat(f.geometry.coordinates as [number, number])
|
.setLngLat(f.geometry.coordinates as [number, number])
|
||||||
.setHTML(
|
.setHTML(
|
||||||
`<div data-testid="airport-popup">` +
|
`<div data-testid="airport-popup">` +
|
||||||
`<strong>${escapeHtml(p.name)}</strong><br/>${escapeHtml(p.icao)}<br/>` +
|
`<strong>${escapeHtml(p.name)}</strong><br/>${escapeHtml(p.icao)}<br/>` +
|
||||||
`<span data-testid="airport-local-time">${localTime} local (approx)</span><br/>` +
|
`<span data-testid="airport-local-time">${localTime} local (approx)</span><br/>` +
|
||||||
`<span data-testid="airport-weather">${w.condition}, wind ${w.windDirDeg}\u00B0 / ${w.windKt} kt, vis ${w.visibilityM} m</span>` +
|
`<span data-testid="airport-weather">${w.condition}, wind ${w.windDirDeg}\u00B0 / ${w.windKt} kt, vis ${w.visibilityM} m</span>` +
|
||||||
|
`<div class="popup-relocate">` + relocateHtml + `<span data-testid="airport-popup-relocate-status"></span></div>` +
|
||||||
`</div>`,
|
`</div>`,
|
||||||
)
|
)
|
||||||
.addTo(map);
|
.addTo(map);
|
||||||
|
|
||||||
|
// Popups are plain HTML, not React — the element only exists after addTo, so wire the
|
||||||
|
// controls via querySelector (the select enables the button once a plane is picked).
|
||||||
|
const el = popup.getElement();
|
||||||
|
const select = el?.querySelector<HTMLSelectElement>('[data-testid="airport-popup-plane"]');
|
||||||
|
const button = el?.querySelector<HTMLButtonElement>('[data-testid="airport-popup-relocate"]');
|
||||||
|
// The status span is always in the popup HTML (even with no grounded planes), so it
|
||||||
|
// exists whenever the select/button do.
|
||||||
|
const statusEl = el?.querySelector<HTMLElement>('[data-testid="airport-popup-relocate-status"]');
|
||||||
|
if (select && button && statusEl) {
|
||||||
|
select.addEventListener('change', () => {
|
||||||
|
button.disabled = select.value === '';
|
||||||
|
});
|
||||||
|
button.addEventListener('click', async () => {
|
||||||
|
const planeId = select.value;
|
||||||
|
if (!planeId || button.disabled) return;
|
||||||
|
button.disabled = true;
|
||||||
|
statusEl.textContent = 'Relocating\u2026';
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/planes/${planeId}/fly`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ destIcao: p.icao }),
|
||||||
|
cache: 'no-store',
|
||||||
|
});
|
||||||
|
const data = (await res.json()) as StateSnapshot & { error?: string };
|
||||||
|
if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
|
||||||
|
applySnapshotRef.current(data); // shared shell state updates immediately, like the panes' runAction
|
||||||
|
statusEl.textContent = 'Relocation started.';
|
||||||
|
} catch (err) {
|
||||||
|
statusEl.textContent = err instanceof Error ? err.message : String(err);
|
||||||
|
button.disabled = false; // allow retry / picking another plane
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const onPlaneClick = (e: maplibregl.MapLayerMouseEvent) => {
|
const onPlaneClick = (e: maplibregl.MapLayerMouseEvent) => {
|
||||||
@@ -224,9 +340,9 @@ export default function FlightMap({ state, hovered }: MapProps) {
|
|||||||
type: 'circle',
|
type: 'circle',
|
||||||
source: AIRPORTS_SOURCE_ID,
|
source: AIRPORTS_SOURCE_ID,
|
||||||
paint: {
|
paint: {
|
||||||
'circle-radius': 3,
|
'circle-radius': 5, // ISS-010 (v0.18.0): bigger — the r=3 dots were hard to click
|
||||||
'circle-color': '#e11d48',
|
'circle-color': '#e11d48',
|
||||||
'circle-stroke-width': 1,
|
'circle-stroke-width': 1.5,
|
||||||
'circle-stroke-color': '#ffffff',
|
'circle-stroke-color': '#ffffff',
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -250,6 +366,27 @@ export default function FlightMap({ state, hovered }: MapProps) {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
// ISS-043 (v0.26.0): dotted queue line — added after routes-legs but BEFORE the hover
|
||||||
|
// layers so a hovered trace still draws on top of it. Muted slate + fine dots reads as
|
||||||
|
// "planned/future", distinct from the solid amber active leg and the [2,2] yellow hover dash.
|
||||||
|
if (!map.getSource(QUEUE_ROUTES_SOURCE_ID)) {
|
||||||
|
map.addSource(QUEUE_ROUTES_SOURCE_ID, {
|
||||||
|
type: 'geojson',
|
||||||
|
data: queuedRoutesGeoJson(stateRef.current?.planes ?? [], airportsIndexRef.current ?? new Map()),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (!map.getLayer(QUEUE_ROUTES_LAYER_ID)) {
|
||||||
|
map.addLayer({
|
||||||
|
id: QUEUE_ROUTES_LAYER_ID,
|
||||||
|
type: 'line',
|
||||||
|
source: QUEUE_ROUTES_SOURCE_ID,
|
||||||
|
paint: {
|
||||||
|
'line-color': '#64748b', // muted slate — planned legs, not actively flying
|
||||||
|
'line-width': 3,
|
||||||
|
'line-dasharray': [0.1, 1.5], // dotted — distinct from solid legs and the [2,2] hover dash
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
if (!map.getSource(PLANES_SOURCE_ID)) {
|
if (!map.getSource(PLANES_SOURCE_ID)) {
|
||||||
map.addSource(PLANES_SOURCE_ID, { type: 'geojson', data: planesGeoJson(stateRef.current) });
|
map.addSource(PLANES_SOURCE_ID, { type: 'geojson', data: planesGeoJson(stateRef.current) });
|
||||||
}
|
}
|
||||||
@@ -317,13 +454,48 @@ export default function FlightMap({ state, hovered }: MapProps) {
|
|||||||
source: AIRPORTS_SOURCE_ID,
|
source: AIRPORTS_SOURCE_ID,
|
||||||
filter: ['any', ['==', ['get', 'icao'], ''], ['==', ['get', 'icao'], '']],
|
filter: ['any', ['==', ['get', 'icao'], ''], ['==', ['get', 'icao'], '']],
|
||||||
paint: {
|
paint: {
|
||||||
'circle-radius': 8, // ring around the base airport circles (r=3)
|
'circle-radius': 9, // ring around the base airport circles (r=5)
|
||||||
'circle-color': 'rgba(0, 0, 0, 0)', // transparent fill — stroke-only ring
|
'circle-color': 'rgba(0, 0, 0, 0)', // transparent fill — stroke-only ring
|
||||||
'circle-stroke-width': 2.5,
|
'circle-stroke-width': 2.5,
|
||||||
'circle-stroke-color': '#facc15',
|
'circle-stroke-color': '#facc15',
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
// ISS-022/025/027 (v0.22.0): the hover route trace — added LAST so it sits above every
|
||||||
|
// other layer, including the highlight rings at its endpoints. Own source: the shared
|
||||||
|
// `routes` source only holds flying legs, never a planned one. Empty until a hover sets data.
|
||||||
|
if (!map.getSource(HOVER_ROUTES_SOURCE_ID)) {
|
||||||
|
map.addSource(HOVER_ROUTES_SOURCE_ID, { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
|
||||||
|
}
|
||||||
|
if (!map.getLayer(HOVER_ROUTE_LAYER_ID)) {
|
||||||
|
map.addLayer({
|
||||||
|
id: HOVER_ROUTE_LAYER_ID,
|
||||||
|
type: 'line',
|
||||||
|
source: HOVER_ROUTES_SOURCE_ID,
|
||||||
|
paint: {
|
||||||
|
'line-color': '#facc15', // matches the airports-highlight ring — one "trace" color
|
||||||
|
'line-width': 4,
|
||||||
|
'line-dasharray': [2, 2], // dashed = planned route, distinct from solid flying legs
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// ISS-022 (v0.22.0): the destination's ring — same geometry as airports-highlight but a
|
||||||
|
// DIFFERENT color so the target stands out over the origin's yellow ring; added last so it
|
||||||
|
// also sits above the hover-route line at its endpoint. Starts filtered to match nothing.
|
||||||
|
if (!map.getLayer(AIRPORTS_TARGET_HIGHLIGHT_LAYER_ID)) {
|
||||||
|
map.addLayer({
|
||||||
|
id: AIRPORTS_TARGET_HIGHLIGHT_LAYER_ID,
|
||||||
|
type: 'circle',
|
||||||
|
source: AIRPORTS_SOURCE_ID,
|
||||||
|
filter: ['==', ['get', 'icao'], ''],
|
||||||
|
paint: {
|
||||||
|
'circle-radius': 9, // same ring size as airports-highlight (r=5 base circles)
|
||||||
|
'circle-color': 'rgba(0, 0, 0, 0)', // transparent fill — stroke-only ring
|
||||||
|
'circle-stroke-width': 3,
|
||||||
|
'circle-stroke-color': '#4ade80', // green — distinct from the yellow endpoint rings
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
// Layer-scoped listeners survive setStyle (they filter by layer id at event
|
// Layer-scoped listeners survive setStyle (they filter by layer id at event
|
||||||
// time), so off+on with the same reference re-wires without duplicating.
|
// time), so off+on with the same reference re-wires without duplicating.
|
||||||
map.off('click', AIRPORTS_LAYER_ID, onAirportClick);
|
map.off('click', AIRPORTS_LAYER_ID, onAirportClick);
|
||||||
|
|||||||
+109
-176
@@ -1,10 +1,11 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useCallback, useEffect, useState } from 'react';
|
import { useState } from 'react';
|
||||||
import type { PackageState, PlaneState, StateSnapshot } from '@/lib/game/state';
|
import type { PackageState, PlaneState, StateSnapshot } from '@/lib/game/state';
|
||||||
import { PLANE_TYPES } from '@/lib/game/catalog';
|
import { PLANE_TYPES, SELL_FRACTION } from '@/lib/game/catalog';
|
||||||
import { abandonPenalty } from '@/lib/game/penalty';
|
import { maxRangeKm } from '@/lib/sim/movement';
|
||||||
import { formatCash, formatDeadlineRelative } from '@/lib/format';
|
import { formatCash, formatDeadlineRelative } from '@/lib/format';
|
||||||
|
import { useGameAction } from '@/lib/useGameAction';
|
||||||
import type { HoverTarget } from './hoverTypes';
|
import type { HoverTarget } from './hoverTypes';
|
||||||
|
|
||||||
interface RightPaneProps {
|
interface RightPaneProps {
|
||||||
@@ -16,27 +17,32 @@ interface RightPaneProps {
|
|||||||
// ISS-002 (v0.15.0): report row hovers to the shell so the map can highlight the plane or
|
// ISS-002 (v0.15.0): report row hovers to the shell so the map can highlight the plane or
|
||||||
// the package's endpoint airports.
|
// the package's endpoint airports.
|
||||||
onHover: (target: HoverTarget | null) => void;
|
onHover: (target: HoverTarget | null) => void;
|
||||||
|
// ISS-008 (v0.17.0): report a failed action to the shell as an error toast — in ADDITION
|
||||||
|
// to the inline pane error, which stays (both surfaces by design).
|
||||||
|
onError?: (message: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const planeName = (p: PlaneState): string => PLANE_TYPES[p.model]?.name ?? p.model;
|
const planeName = (p: PlaneState): string => PLANE_TYPES[p.model]?.name ?? p.model;
|
||||||
|
|
||||||
// Packages occupying a plane's slots — 'loaded' cargo plus 'expired' cargo, which
|
// Cargo weight (kg) occupying a plane's payload — 'loaded' cargo plus 'expired'
|
||||||
// keeps its slot until it is abandoned or the plane lands at its destination.
|
// cargo, which keeps its space until it is abandoned or the plane lands at its
|
||||||
export function slotsUsedFor(state: StateSnapshot, planeId: string): number {
|
// destination.
|
||||||
return state.packages.filter(
|
export function cargoWeightFor(state: StateSnapshot, planeId: string): number {
|
||||||
(p) => p.planeId === planeId && (p.status === 'loaded' || p.status === 'expired'),
|
return state.packages
|
||||||
).length;
|
.filter((p) => p.planeId === planeId && (p.status === 'loaded' || p.status === 'expired'))
|
||||||
|
.reduce((sum, p) => sum + p.weightKg, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Planes that can load `pkg` right now: GROUNDED at the package's origin with a
|
// Planes that can load `pkg` right now: GROUNDED at the package's origin with enough
|
||||||
// free slot (capacity from the snapshot catalog). The Load button is enabled iff
|
// payload room for it (maxPayloadKg from the snapshot catalog). The Load button is
|
||||||
// this list is non-empty; exactly one entry loads directly, several show a picker.
|
// enabled iff this list is non-empty; exactly one entry loads directly, several show a picker.
|
||||||
export function loadEligiblePlanes(state: StateSnapshot, pkg: PackageState): PlaneState[] {
|
export function loadEligiblePlanes(state: StateSnapshot, pkg: PackageState): PlaneState[] {
|
||||||
return state.planes.filter((p) => {
|
return state.planes.filter((p) => {
|
||||||
if (p.status !== 'available') return false;
|
if (p.status !== 'available') return false;
|
||||||
if (p.locationIcao !== pkg.originIcao) return false;
|
if (p.locationIcao !== pkg.originIcao) return false;
|
||||||
const capacity = state.catalog.find((e) => e.model === p.model)?.capacity ?? 0;
|
const maxPayloadKg = state.catalog.find((e) => e.model === p.model)?.maxPayloadKg ?? 0;
|
||||||
return slotsUsedFor(state, p.id) < capacity;
|
// Mirrors the server check in lib/game/actions.ts loadPackage.
|
||||||
|
return cargoWeightFor(state, p.id) + pkg.weightKg <= maxPayloadKg;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -104,48 +110,23 @@ function LoadControls({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function RightPane({ state, loading, applySnapshot, onHover }: RightPaneProps) {
|
export default function RightPane({ state, loading, applySnapshot, onHover, onError }: RightPaneProps) {
|
||||||
const [busy, setBusy] = useState(false);
|
// ISS-021 (v0.20.0): shared action runner — busy gate, inline pane error + shell toast on
|
||||||
// Inline error from a failed action — auto-clears on the next successful poll (the shell's
|
// failure, full post-action snapshot pushed into the shared state on success.
|
||||||
// snapshot prop changes every tick) or the next successful action.
|
const { runAction, busy, actionError } = useGameAction(state, applySnapshot, onError);
|
||||||
const [actionError, setActionError] = useState<string | null>(null);
|
|
||||||
useEffect(() => {
|
|
||||||
if (state !== null) setActionError(null);
|
|
||||||
}, [state]);
|
|
||||||
|
|
||||||
// Market picker selections — same "effective selection" pattern as LoadControls: the
|
// Market picker selections — same "effective selection" pattern as LoadControls: the
|
||||||
// user's pick while it stays valid, else a sensible default (first catalog entry / first plane).
|
// user's pick while it stays valid, else a sensible default (first catalog entry / first plane).
|
||||||
const [buyModelId, setBuyModelId] = useState<string | null>(null);
|
const [buyModelId, setBuyModelId] = useState<string | null>(null);
|
||||||
const [sellPlaneId, setSellPlaneId] = useState<string | null>(null);
|
const [sellPlaneId, setSellPlaneId] = useState<string | null>(null);
|
||||||
const [refuelPlaneId, setRefuelPlaneId] = useState<string | null>(null);
|
|
||||||
|
|
||||||
// POST an action endpoint. Every success returns the FULL post-action snapshot (v0.8.0
|
// v0.28.0 (ISS-047): Jobs / Planes market tabs — the inactive tab's content unmounts.
|
||||||
// convention) — pushed into the shared state immediately; a 4xx {error} body becomes the
|
const [activeTab, setActiveTab] = useState<'jobs' | 'planes'>('jobs');
|
||||||
// inline pane error and the stale UI stays until the next poll. Buttons are disabled while
|
|
||||||
// a request is in flight, so at most one action runs at a time.
|
// ISS-023 (v0.21.0): the Relocate row moved to the left pane — it belongs with everything else
|
||||||
const runAction = useCallback(
|
// about our planes, not in the market. Its state + /api/airports fetch went with it.
|
||||||
async (path: string, body?: unknown) => {
|
// ISS-035 (v0.23.0): same for the Refuel-to-full row — its state + derived values moved to the
|
||||||
if (busy) return;
|
// left pane's "Refuel" section next to Relocate.
|
||||||
setBusy(true);
|
|
||||||
try {
|
|
||||||
const res = await fetch(path, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: body === undefined ? undefined : JSON.stringify(body),
|
|
||||||
cache: 'no-store',
|
|
||||||
});
|
|
||||||
const data = (await res.json()) as StateSnapshot & { error?: string };
|
|
||||||
if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
|
|
||||||
setActionError(null);
|
|
||||||
applySnapshot(data);
|
|
||||||
} catch (err) {
|
|
||||||
setActionError(err instanceof Error ? err.message : String(err));
|
|
||||||
} finally {
|
|
||||||
setBusy(false);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
[applySnapshot, busy],
|
|
||||||
);
|
|
||||||
|
|
||||||
if (loading && !state) {
|
if (loading && !state) {
|
||||||
return (
|
return (
|
||||||
@@ -160,33 +141,44 @@ export default function RightPane({ state, loading, applySnapshot, onHover }: Ri
|
|||||||
const clockMs = state.simState.clockMs;
|
const clockMs = state.simState.clockMs;
|
||||||
const open = state.packages.filter((p) => p.status === 'open');
|
const open = state.packages.filter((p) => p.status === 'open');
|
||||||
|
|
||||||
// On board (v0.12.0): every plane that carries cargo or is mid-flight gets a block —
|
|
||||||
// its loaded/expired packages with fly-to-destination + abandon controls, and flying
|
|
||||||
// planes show their current leg.
|
|
||||||
const onboard = state.planes.filter(
|
|
||||||
(p) => p.status === 'flying' || slotsUsedFor(state, p.id) > 0,
|
|
||||||
);
|
|
||||||
|
|
||||||
const catalog = state.catalog;
|
const catalog = state.catalog;
|
||||||
const buyEntry = catalog.find((e) => e.model === buyModelId) ?? catalog[0] ?? null;
|
const buyEntry = catalog.find((e) => e.model === buyModelId) ?? catalog[0] ?? null;
|
||||||
|
|
||||||
const grounded = state.planes.filter((p) => p.status === 'available');
|
const grounded = state.planes.filter((p) => p.status === 'available');
|
||||||
const sellPlane = state.planes.find((p) => p.id === sellPlaneId && p.status === 'available') ?? grounded[0] ?? null;
|
const sellPlane = state.planes.find((p) => p.id === sellPlaneId && p.status === 'available') ?? grounded[0] ?? null;
|
||||||
const refuelable = grounded.filter((p) => p.fuel < p.maxFuel);
|
|
||||||
const refuelPlane =
|
|
||||||
state.planes.find((p) => p.id === refuelPlaneId && p.status === 'available' && p.fuel < p.maxFuel) ??
|
|
||||||
refuelable[0] ??
|
|
||||||
null;
|
|
||||||
|
|
||||||
// Previews computed client-side from the snapshot's catalog + economy constants (v0.10.0).
|
// Previews computed client-side from the snapshot's catalog + economy constants (v0.10.0).
|
||||||
const sellEntry = sellPlane ? catalog.find((e) => e.model === sellPlane.model) : undefined;
|
const sellEntry = sellPlane ? catalog.find((e) => e.model === sellPlane.model) : undefined;
|
||||||
const sellPayout = sellEntry ? Math.round(sellEntry.price * state.sellFraction * 100) / 100 : null;
|
const sellPayout = sellEntry ? Math.round(sellEntry.price * state.sellFraction * 100) / 100 : null;
|
||||||
const refuelCost = refuelPlane ? (refuelPlane.maxFuel - refuelPlane.fuel) * state.fuelPricePerL : null;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<aside data-testid="right-pane" className="pane right-pane">
|
<aside data-testid="right-pane" className="pane right-pane">
|
||||||
<h2 className="pane-title">Jobs & Market</h2>
|
<h2 className="pane-title">Jobs & Market</h2>
|
||||||
|
|
||||||
|
{/* v0.28.0 (ISS-047): Jobs / Planes market tabs — the inactive tab's content unmounts. */}
|
||||||
|
<div className="pane-tabs" role="tablist">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid="tab-jobs"
|
||||||
|
role="tab"
|
||||||
|
aria-selected={activeTab === 'jobs'}
|
||||||
|
className="tab-btn"
|
||||||
|
onClick={() => setActiveTab('jobs')}
|
||||||
|
>
|
||||||
|
Jobs
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid="tab-planes-market"
|
||||||
|
role="tab"
|
||||||
|
aria-selected={activeTab === 'planes'}
|
||||||
|
className="tab-btn"
|
||||||
|
onClick={() => setActiveTab('planes')}
|
||||||
|
>
|
||||||
|
Planes market
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{activeTab === 'jobs' && (
|
||||||
<section className="pane-section">
|
<section className="pane-section">
|
||||||
<h3 className="pane-heading">Packages</h3>
|
<h3 className="pane-heading">Packages</h3>
|
||||||
{open.length === 0 ? (
|
{open.length === 0 ? (
|
||||||
@@ -218,6 +210,16 @@ export default function RightPane({ state, loading, applySnapshot, onHover }: Ri
|
|||||||
Load
|
Load
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
{/* ISS-047 part B (v0.29.0): dismiss the job — it leaves the market permanently, no penalty. */}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid={`ignore-${pkg.id}`}
|
||||||
|
className="pane-btn"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => void runAction(`/api/packages/${pkg.id}/ignore`)}
|
||||||
|
>
|
||||||
|
Ignore
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div className="contract-sub">
|
<div className="contract-sub">
|
||||||
<span data-testid={`open-package-reward-${pkg.id}`}>{formatCash(pkg.reward)}</span>
|
<span data-testid={`open-package-reward-${pkg.id}`}>{formatCash(pkg.reward)}</span>
|
||||||
@@ -232,85 +234,11 @@ export default function RightPane({ state, loading, applySnapshot, onHover }: Ri
|
|||||||
</ul>
|
</ul>
|
||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
|
)}
|
||||||
|
|
||||||
<section className="pane-section">
|
{/* ISS-021 (v0.20.0): the On board section moved to the left pane (between Fleet and Time). */}
|
||||||
<h3 className="pane-heading">On board</h3>
|
|
||||||
{onboard.length === 0 ? (
|
|
||||||
<p className="pane-muted">Nothing on board.</p>
|
|
||||||
) : (
|
|
||||||
onboard.map((plane) => {
|
|
||||||
const cargo = state.packages.filter(
|
|
||||||
(pkg) => pkg.planeId === plane.id && (pkg.status === 'loaded' || pkg.status === 'expired'),
|
|
||||||
);
|
|
||||||
return (
|
|
||||||
// ISS-002: hovering the on-board block (including its cargo rows) highlights the plane.
|
|
||||||
// Handlers live only on the outer div — React's enter/leave don't fire when moving to a
|
|
||||||
// child, so this covers the whole block without flicker between sub-elements.
|
|
||||||
<div
|
|
||||||
key={plane.id}
|
|
||||||
data-testid={`onboard-${plane.id}`}
|
|
||||||
className="onboard-block"
|
|
||||||
onMouseEnter={() => onHover({ kind: 'plane', id: plane.id })}
|
|
||||||
onMouseLeave={() => onHover(null)}
|
|
||||||
>
|
|
||||||
<div className="contract-main">
|
|
||||||
<span className="plane-model">{planeName(plane)}</span>
|
|
||||||
{plane.status === 'flying' ? (
|
|
||||||
<>
|
|
||||||
<span className="plane-status status-flying">in flight</span>
|
|
||||||
{plane.destName && (
|
|
||||||
<span data-testid={`plane-leg-${plane.id}`} className="contract-route">
|
|
||||||
{plane.locationName} → {plane.destName}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<span className="plane-status status-available">{plane.locationIcao}</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{cargo.map((pkg) => {
|
|
||||||
const penalty = abandonPenalty(pkg, clockMs);
|
|
||||||
return (
|
|
||||||
<div key={pkg.id} data-testid={`onboard-package-${pkg.id}`} className="contract-row">
|
|
||||||
<div className="contract-main">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
data-testid={`fly-to-${pkg.id}`}
|
|
||||||
className="pane-btn"
|
|
||||||
disabled={busy || plane.status !== 'available'}
|
|
||||||
onClick={() => void runAction(`/api/planes/${plane.id}/fly`, { destIcao: pkg.destIcao })}
|
|
||||||
>
|
|
||||||
Fly to {pkg.destName}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
data-testid={`abandon-${pkg.id}`}
|
|
||||||
className="pane-btn"
|
|
||||||
disabled={busy || plane.status !== 'available'}
|
|
||||||
onClick={() => void runAction(`/api/packages/${pkg.id}/abandon`)}
|
|
||||||
>
|
|
||||||
Abandon{' '}
|
|
||||||
<span data-testid={`abandon-penalty-${pkg.id}`}>−{formatCash(penalty)}</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div className="contract-sub">
|
|
||||||
<span>{pkg.originName} → {pkg.destName}</span>
|
|
||||||
<span>{formatCash(pkg.reward)}</span>
|
|
||||||
{pkg.status === 'expired' ? (
|
|
||||||
<span data-testid={`onboard-expired-${pkg.id}`}>expired</span>
|
|
||||||
) : (
|
|
||||||
<span>{formatDeadlineRelative(pkg.deadlineSimTime, clockMs)}</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})
|
|
||||||
)}
|
|
||||||
</section>
|
|
||||||
|
|
||||||
|
{activeTab === 'planes' && (
|
||||||
<section className="pane-section">
|
<section className="pane-section">
|
||||||
<h3 className="pane-heading">Market</h3>
|
<h3 className="pane-heading">Market</h3>
|
||||||
|
|
||||||
@@ -372,43 +300,48 @@ export default function RightPane({ state, loading, applySnapshot, onHover }: Ri
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="market-row">
|
{/* ISS-023 (v0.21.0): the Relocate row moved to the left pane's "Relocate" section. */}
|
||||||
{refuelable.length === 0 ? (
|
{/* ISS-035 (v0.23.0): the Refuel-to-full row moved to the left pane's "Refuel" section, next to Relocate. */}
|
||||||
<span data-testid="market-refuel-none" className="pane-muted">
|
|
||||||
All tanks full.
|
{/* v0.28.0 (ISS-047): tech-spec panel per catalog type — progression order (price ascending).
|
||||||
</span>
|
All values come from the snapshot's catalog; max range is the weighted-model closed form. */}
|
||||||
) : (
|
{[...catalog].sort((a, b) => a.price - b.price).map((e) => (
|
||||||
<>
|
<div key={e.model} className="plane-type-card" data-testid={`plane-type-${e.model}`}>
|
||||||
<select
|
<h4 className="plane-type-name">{e.label}</h4>
|
||||||
data-testid="market-refuel-plane"
|
<div className="stat-row">
|
||||||
aria-label="Plane to refuel"
|
<span>Buy</span>
|
||||||
value={refuelPlane?.id ?? ''}
|
<strong>{formatCash(e.price)}</strong>
|
||||||
onChange={(e) => setRefuelPlaneId(e.target.value || null)}
|
|
||||||
>
|
|
||||||
{refuelable.map((p) => (
|
|
||||||
<option key={p.id} value={p.id}>
|
|
||||||
{planeName(p)} — {Math.round(p.fuel)} / {p.maxFuel} L
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
<span data-testid="market-refuel-cost" className="market-preview">
|
|
||||||
{refuelCost !== null ? formatCash(refuelCost) : ''}
|
|
||||||
</span>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
data-testid="market-refuel"
|
|
||||||
className="pane-btn"
|
|
||||||
disabled={busy || refuelPlane === null}
|
|
||||||
onClick={() => {
|
|
||||||
if (refuelPlane) void runAction(`/api/planes/${refuelPlane.id}/refuel`);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Refuel
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
|
<div className="stat-row">
|
||||||
|
<span>Sell</span>
|
||||||
|
<strong>{formatCash(Math.round(e.price * SELL_FRACTION * 100) / 100)}</strong>
|
||||||
|
</div>
|
||||||
|
<div className="stat-row">
|
||||||
|
<span>Payload</span>
|
||||||
|
<strong>{(e.maxPayloadKg / 1000).toFixed(1)}t</strong>
|
||||||
|
</div>
|
||||||
|
<div className="stat-row">
|
||||||
|
<span>Cruise speed</span>
|
||||||
|
<strong>{e.speedKmh} km/h</strong>
|
||||||
|
</div>
|
||||||
|
<div className="stat-row">
|
||||||
|
<span>Fuel burn</span>
|
||||||
|
<strong>{e.burnPerKm} L/km</strong>
|
||||||
|
</div>
|
||||||
|
<div className="stat-row">
|
||||||
|
<span>Max fuel</span>
|
||||||
|
<strong>{e.maxFuel} L</strong>
|
||||||
|
</div>
|
||||||
|
<div className="stat-row">
|
||||||
|
<span>Max range</span>
|
||||||
|
<strong data-testid={`plane-type-range-${e.model}`}>
|
||||||
|
{Math.round(maxRangeKm(e.burnPerKm, e.emptyWeightKg, e.maxFuel))} km
|
||||||
|
</strong>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
</section>
|
</section>
|
||||||
|
)}
|
||||||
|
|
||||||
{actionError && <p data-testid="right-error" className="pane-error">{actionError}</p>}
|
{actionError && <p data-testid="right-error" className="pane-error">{actionError}</p>}
|
||||||
</aside>
|
</aside>
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import type { Toast } from '@/lib/useToasts';
|
||||||
|
|
||||||
|
// ISS-008 (v0.17.0): the bottom-right toast stack — action errors and game events derived
|
||||||
|
// from snapshot diffs. Fixed-position overlay above the map; each item auto-dismisses via
|
||||||
|
// the hook's TTL or its × button.
|
||||||
|
export default function ToastStack({ toasts, onDismiss }: { toasts: Toast[]; onDismiss?: (id: number) => void }) {
|
||||||
|
if (toasts.length === 0) return null;
|
||||||
|
return (
|
||||||
|
<div className="toasts" role="status">
|
||||||
|
{toasts.map((t) => (
|
||||||
|
<div key={t.id} data-testid="toast" className={`toast toast-${t.kind}`}>
|
||||||
|
<span>{t.message}</span>
|
||||||
|
{onDismiss && (
|
||||||
|
<button type="button" data-testid={`toast-dismiss-${t.id}`} className="toast-close" onClick={() => onDismiss(t.id)}>
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,7 +1,12 @@
|
|||||||
// ISS-002 — what a side-panel hover highlights on the map (v0.15.0): a plane marker
|
// ISS-002 — what a side-panel hover highlights on the map (v0.15.0): a plane marker
|
||||||
// (+ its route leg if flying) or both endpoint airports of an open package. The shell
|
// (+ its route leg if flying) or both endpoint airports of an open package. The shell
|
||||||
// owns this state and passes it to <Map>; panes report it via their onHover callback.
|
// owns this state and passes it to <Map>; panes report it via their onHover callback.
|
||||||
|
// ISS-022/025/027 (v0.22.0): any target carrying two ICAOs also makes the map draw the full
|
||||||
|
// great-circle trace between them — package hovers carry origin→dest, 'route' hovers (the
|
||||||
|
// Relocate panel) carry fromIcao→toIcao; a package hover may additionally name its plane so
|
||||||
|
// that plane's halo stays lit alongside the trace.
|
||||||
|
|
||||||
export type HoverTarget =
|
export type HoverTarget =
|
||||||
| { kind: 'plane'; id: string }
|
| { kind: 'plane'; id: string }
|
||||||
| { kind: 'package'; originIcao: string; destIcao: string };
|
| { kind: 'package'; originIcao: string; destIcao: string; planeId?: string }
|
||||||
|
| { kind: 'route'; fromIcao: string; toIcao: string };
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
import { pendingScaleConfirmed } from './LeftPane';
|
import { pendingScaleConfirmed, retrySimPost, SIM_POST_MAX_ATTEMPTS, SIM_POST_RETRY_DELAY_MS } from './LeftPane';
|
||||||
|
|
||||||
// ISS-001 — the optimistic slider value is cleared exactly when a rendered snapshot confirms
|
// ISS-001 — the optimistic slider value is cleared exactly when a rendered snapshot confirms
|
||||||
// it (server scale === pending), never earlier. Clearing at commit time would snap the pointer
|
// it (server scale === pending), never earlier. Clearing at commit time would snap the pointer
|
||||||
@@ -22,3 +22,70 @@ describe('pendingScaleConfirmed', () => {
|
|||||||
expect(pendingScaleConfirmed(1, 1)).toBe(true); // committing the current value confirms immediately
|
expect(pendingScaleConfirmed(1, 1)).toBe(true); // committing the current value confirms immediately
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ISS-008 fix (CI runs #44/#47): a dropped POST /api/sim must be retried before surfacing the
|
||||||
|
// error — up to SIM_POST_MAX_ATTEMPTS tries with SIM_POST_RETRY_DELAY_MS between them, and a newer
|
||||||
|
// intent supersedes the in-flight body instead of waiting out its retries.
|
||||||
|
|
||||||
|
describe('retrySimPost', () => {
|
||||||
|
it('pins the retry budget: 3 attempts total, ~500 ms backoff', () => {
|
||||||
|
expect(SIM_POST_MAX_ATTEMPTS).toBe(3);
|
||||||
|
expect(SIM_POST_RETRY_DELAY_MS).toBe(500);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('succeeds on the first attempt without sleeping or retrying', async () => {
|
||||||
|
const post = vi.fn(async () => {});
|
||||||
|
const sleep = vi.fn(async () => {});
|
||||||
|
await expect(retrySimPost(post, () => false, sleep)).resolves.toEqual({ ok: true });
|
||||||
|
expect(post).toHaveBeenCalledTimes(1);
|
||||||
|
expect(sleep).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('retries with the backoff delay and succeeds on a later attempt', async () => {
|
||||||
|
let calls = 0;
|
||||||
|
const post = vi.fn(async () => {
|
||||||
|
if (++calls < 3) throw new Error('dropped');
|
||||||
|
});
|
||||||
|
const sleep = vi.fn(async () => {});
|
||||||
|
await expect(retrySimPost(post, () => false, sleep)).resolves.toEqual({ ok: true });
|
||||||
|
expect(post).toHaveBeenCalledTimes(3);
|
||||||
|
expect(sleep).toHaveBeenCalledTimes(2); // one backoff between each pair of attempts
|
||||||
|
expect(sleep).toHaveBeenCalledWith(SIM_POST_RETRY_DELAY_MS);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('gives up after the final attempt with the last error (no trailing sleep)', async () => {
|
||||||
|
const err = new Error('down');
|
||||||
|
const post = vi.fn(async () => {
|
||||||
|
throw err;
|
||||||
|
});
|
||||||
|
const sleep = vi.fn(async () => {});
|
||||||
|
const result = await retrySimPost(post, () => false, sleep);
|
||||||
|
expect(result.ok).toBe(false);
|
||||||
|
if (!result.ok) {
|
||||||
|
expect(result.reason).toBe('exhausted');
|
||||||
|
if (result.reason === 'exhausted') expect(result.error).toBe(err); // the LAST attempt's error
|
||||||
|
}
|
||||||
|
expect(post).toHaveBeenCalledTimes(SIM_POST_MAX_ATTEMPTS);
|
||||||
|
expect(sleep).toHaveBeenCalledTimes(SIM_POST_MAX_ATTEMPTS - 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stops retrying once a newer intent supersedes the in-flight body (no further attempts or sleeps)', async () => {
|
||||||
|
let calls = 0;
|
||||||
|
const post = vi.fn(async () => {
|
||||||
|
calls++; // flip "superseded" right after the first failure, like a queued commitNow would
|
||||||
|
throw new Error('dropped');
|
||||||
|
});
|
||||||
|
const sleep = vi.fn(async () => {});
|
||||||
|
await expect(retrySimPost(post, () => calls >= 1, sleep)).resolves.toEqual({ ok: false, reason: 'superseded' });
|
||||||
|
expect(post).toHaveBeenCalledTimes(1); // the caller's loop sends the newer body instead
|
||||||
|
expect(sleep).not.toHaveBeenCalled(); // supersede is checked before the backoff sleep
|
||||||
|
});
|
||||||
|
|
||||||
|
it('never even sends a body that is already superseded', async () => {
|
||||||
|
const post = vi.fn(async () => {});
|
||||||
|
const sleep = vi.fn(async () => {});
|
||||||
|
await expect(retrySimPost(post, () => true, sleep)).resolves.toEqual({ ok: false, reason: 'superseded' });
|
||||||
|
expect(post).not.toHaveBeenCalled();
|
||||||
|
expect(sleep).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import { loadEligiblePlanes, slotsUsedFor } from './RightPane';
|
import { cargoWeightFor, loadEligiblePlanes } from './RightPane';
|
||||||
import type { PackageState, PlaneState, StateSnapshot } from '@/lib/game/state';
|
import type { PackageState, PlaneState, StateSnapshot } from '@/lib/game/state';
|
||||||
|
|
||||||
// v0.12.0 — the package-model picker rules: a plane can LOAD a package only while
|
// v0.12.0 (weight model v0.27.0) — the package-model picker rules: a plane can LOAD a
|
||||||
// it is GROUNDED at the package's origin with a free slot (capacity from the
|
// package only while it is GROUNDED at the package's origin with enough payload room for
|
||||||
// snapshot catalog; expired packages still occupy theirs). The Load button acts
|
// it (maxPayloadKg from the snapshot catalog; expired packages still occupy theirs). The
|
||||||
// directly on the single eligible plane, or shows a picker when several qualify.
|
// Load button acts directly on the single eligible plane, or shows a picker when several qualify.
|
||||||
|
|
||||||
const CATALOG = [
|
const CATALOG = [
|
||||||
{ model: 'atr72', label: 'ATR 72-600', price: 200_000, maxFuel: 6300, burnPerKm: 1.75, speedKmh: 510, capacity: 6 },
|
{ model: 'atr72', label: 'ATR 72-600', price: 200_000, maxFuel: 6300, burnPerKm: 1.75, emptyWeightKg: 9_300, speedKmh: 510, maxPayloadKg: 4_800 },
|
||||||
];
|
];
|
||||||
|
|
||||||
function plane(over: Partial<PlaneState> & Pick<PlaneState, 'id'>): PlaneState {
|
function plane(over: Partial<PlaneState> & Pick<PlaneState, 'id'>): PlaneState {
|
||||||
@@ -24,6 +24,7 @@ function plane(over: Partial<PlaneState> & Pick<PlaneState, 'id'>): PlaneState {
|
|||||||
departureSimTime: null,
|
departureSimTime: null,
|
||||||
lat: 50,
|
lat: 50,
|
||||||
lon: 8.5,
|
lon: 8.5,
|
||||||
|
queue: [],
|
||||||
...over,
|
...over,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -37,6 +38,7 @@ function pkg(over: Partial<PackageState> & Pick<PackageState, 'id'>): PackageSta
|
|||||||
reward: 1000,
|
reward: 1000,
|
||||||
cargoType: 'mail',
|
cargoType: 'mail',
|
||||||
cargoCount: 4,
|
cargoCount: 4,
|
||||||
|
weightKg: 1_000,
|
||||||
deadlineSimTime: 1_000_000,
|
deadlineSimTime: 1_000_000,
|
||||||
status: 'open',
|
status: 'open',
|
||||||
planeId: null,
|
planeId: null,
|
||||||
@@ -57,27 +59,27 @@ function snap(planes: PlaneState[], packages: PackageState[] = []): StateSnapsho
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
describe('slotsUsedFor', () => {
|
describe('cargoWeightFor', () => {
|
||||||
it('counts loaded AND expired packages bound to the plane (both occupy a slot)', () => {
|
it('sums the weight of loaded AND expired packages bound to the plane (both occupy payload)', () => {
|
||||||
const s = snap(
|
const s = snap(
|
||||||
[plane({ id: 'p1' })],
|
[plane({ id: 'p1' })],
|
||||||
[
|
[
|
||||||
pkg({ id: 'a', status: 'loaded', planeId: 'p1' }),
|
pkg({ id: 'a', status: 'loaded', planeId: 'p1', weightKg: 800 }),
|
||||||
pkg({ id: 'b', status: 'expired', planeId: 'p1' }),
|
pkg({ id: 'b', status: 'expired', planeId: 'p1', weightKg: 500 }),
|
||||||
pkg({ id: 'c', status: 'open', planeId: null }), // not on any plane
|
pkg({ id: 'c', status: 'open', planeId: null, weightKg: 9_000 }), // not on any plane
|
||||||
pkg({ id: 'd', status: 'delivered', planeId: 'p1' }), // terminal — slot long freed
|
pkg({ id: 'd', status: 'delivered', planeId: 'p1', weightKg: 700 }), // terminal — payload long freed
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
expect(slotsUsedFor(s, 'p1')).toBe(2);
|
expect(cargoWeightFor(s, 'p1')).toBe(1_300);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('is 0 for a plane with no bound cargo', () => {
|
it('is 0 for a plane with no bound cargo', () => {
|
||||||
expect(slotsUsedFor(snap([plane({ id: 'p1' })]), 'p1')).toBe(0);
|
expect(cargoWeightFor(snap([plane({ id: 'p1' })]), 'p1')).toBe(0);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('loadEligiblePlanes (Load button eligibility)', () => {
|
describe('loadEligiblePlanes (Load button eligibility)', () => {
|
||||||
it('includes only grounded planes at the package origin with a free slot', () => {
|
it('includes only grounded planes at the package origin with enough payload room', () => {
|
||||||
const s = snap([
|
const s = snap([
|
||||||
plane({ id: 'at-origin' }), // eligible
|
plane({ id: 'at-origin' }), // eligible
|
||||||
plane({ id: 'elsewhere', locationIcao: 'LEMD' }), // wrong airport
|
plane({ id: 'elsewhere', locationIcao: 'LEMD' }), // wrong airport
|
||||||
@@ -86,18 +88,23 @@ describe('loadEligiblePlanes (Load button eligibility)', () => {
|
|||||||
expect(loadEligiblePlanes(s, pkg({ id: 'x' })).map((p) => p.id)).toEqual(['at-origin']);
|
expect(loadEligiblePlanes(s, pkg({ id: 'x' })).map((p) => p.id)).toEqual(['at-origin']);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('excludes a plane whose slots are full (capacity from the catalog)', () => {
|
it('a plane with partial payload can still load a package that fits', () => {
|
||||||
const packages = Array.from({ length: 6 }, (_, i) =>
|
const s = snap([plane({ id: 'partial' })], [pkg({ id: 'onboard', status: 'loaded', planeId: 'partial', weightKg: 3_000 })]);
|
||||||
pkg({ id: `fill-${i}`, status: 'loaded', planeId: 'full' }),
|
expect(loadEligiblePlanes(s, pkg({ id: 'x' })).map((p) => p.id)).toEqual(['partial']); // 3000 + 1000 ≤ 4800
|
||||||
|
});
|
||||||
|
|
||||||
|
it('excludes a plane whose payload is full (maxPayloadKg from the catalog)', () => {
|
||||||
|
const packages = Array.from({ length: 4 }, (_, i) =>
|
||||||
|
pkg({ id: `fill-${i}`, status: 'loaded', planeId: 'full', weightKg: 1_200 }), // 4 × 1200 = 4800
|
||||||
);
|
);
|
||||||
const s = snap([plane({ id: 'full' })], packages);
|
const s = snap([plane({ id: 'full' })], packages);
|
||||||
expect(loadEligiblePlanes(s, pkg({ id: 'x' }))).toEqual([]);
|
expect(loadEligiblePlanes(s, pkg({ id: 'x' }))).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('a full plane with one slot freed by an expired package still counts as full', () => {
|
it('a plane at its limit with an expired package still counts as full', () => {
|
||||||
const packages = [
|
const packages = [
|
||||||
...Array.from({ length: 5 }, (_, i) => pkg({ id: `fill-${i}`, status: 'loaded', planeId: 'full' })),
|
...Array.from({ length: 4 }, (_, i) => pkg({ id: `fill-${i}`, status: 'loaded', planeId: 'full', weightKg: 960 })),
|
||||||
pkg({ id: 'exp', status: 'expired', planeId: 'full' }), // occupies its slot
|
pkg({ id: 'exp', status: 'expired', planeId: 'full', weightKg: 960 }), // occupies its payload — 5 × 960 = 4800
|
||||||
];
|
];
|
||||||
const s = snap([plane({ id: 'full' })], packages);
|
const s = snap([plane({ id: 'full' })], packages);
|
||||||
expect(loadEligiblePlanes(s, pkg({ id: 'x' }))).toEqual([]);
|
expect(loadEligiblePlanes(s, pkg({ id: 'x' }))).toEqual([]);
|
||||||
@@ -113,7 +120,7 @@ describe('loadEligiblePlanes (Load button eligibility)', () => {
|
|||||||
expect(loadEligiblePlanes(s, pkg({ id: 'x' }))).toEqual([]);
|
expect(loadEligiblePlanes(s, pkg({ id: 'x' }))).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('a plane with an unknown model has no capacity → never eligible', () => {
|
it('a plane with an unknown model has no maxPayloadKg in the catalog → never eligible', () => {
|
||||||
const s = snap([plane({ id: 'mystery', model: 'mystery' })]);
|
const s = snap([plane({ id: 'mystery', model: 'mystery' })]);
|
||||||
expect(loadEligiblePlanes(s, pkg({ id: 'x' }))).toEqual([]);
|
expect(loadEligiblePlanes(s, pkg({ id: 'x' }))).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|||||||
+96
-34
@@ -3,21 +3,31 @@ import { expect, test } from '@playwright/test';
|
|||||||
|
|
||||||
// v0.12.0 package model against the live origin (https://flight.dev.kkhost.pl):
|
// v0.12.0 package model against the live origin (https://flight.dev.kkhost.pl):
|
||||||
// the full core loop through the UI — hook creates a short package at EDDF → Load
|
// the full core loop through the UI — hook creates a short package at EDDF → Load
|
||||||
// via the right pane → click its destination in the on-board list → fly at 1000× →
|
// via the right pane → click its destination in the on-board list (left pane since
|
||||||
|
// v0.20.0, ISS-021) → fly at 1000× →
|
||||||
// arrival delivers EXACTLY the reward + rep; abandon deducts exactly the formula
|
// arrival delivers EXACTLY the reward + rep; abandon deducts exactly the formula
|
||||||
// penalty while grounded; expired packages deliver/abandon with no reward and no
|
// penalty while grounded; expired packages deliver/abandon with no reward and no
|
||||||
// penalty. Mirrors lib/game/penalty.ts for exact-value assertions.
|
// penalty. Mirrors lib/game/penalty.ts for exact-value assertions.
|
||||||
|
|
||||||
const SCALE = 1000; // fastest sim speed (v0.14.0 ladder top) — keeps flights to seconds of real time
|
const SCALE = 1000; // fastest sim speed (v0.14.0 ladder top) — keeps flights to seconds of real time
|
||||||
const HUB = 'EDDF'; // Frankfurt Main — the seeded starter plane's home base (lib/game/seed.ts)
|
const HUB = 'EDDF'; // Frankfurt Main — the seeded starter plane's home base (lib/game/seed.ts)
|
||||||
const FAR = 'LEZL'; // Seville — one-way burn 3174 L > half tank, so the return leg is unfuelable
|
const FAR = 'LEZL'; // Seville — a long leg: under the v0.16.0 weighted model a full tank covers the
|
||||||
|
// round trip, but the return leaves too little for another outbound
|
||||||
|
|
||||||
// Mirrors lib/sim/movement.ts + lib/game/catalog.ts (atr72).
|
// Mirrors lib/sim/movement.ts (v0.16.0 weight-proportional burn) + lib/game/catalog.ts (atr72).
|
||||||
const BURN_PER_KM = 1.75;
|
const FUEL_DENSITY_KG_PER_L = 0.8; // Jet-A1 density — must match FUEL_DENSITY_KG_PER_L in movement.ts
|
||||||
const FUEL_PRICE_PER_L = 0.8;
|
const FUEL_PRICE_PER_L = 0.8; // must match catalog.ts
|
||||||
const REP_BASE = 1; // lib/sim/engine.ts
|
const REP_BASE = 1; // lib/sim/engine.ts
|
||||||
const REP_PER_KM = 0.0005;
|
const REP_PER_KM = 0.0005;
|
||||||
|
|
||||||
|
// Fuel remaining after distanceKm from startFuel — closed form of dF/dx = −k(We + ρF),
|
||||||
|
// k calibrated so a full tank burns exactly burnPerKm (mirrors fuelAtWeighted).
|
||||||
|
function fuelAfter(startFuel: number, burnPerKm: number, emptyWeightKg: number, maxFuel: number, distanceKm: number): number {
|
||||||
|
const k = burnPerKm / (emptyWeightKg + FUEL_DENSITY_KG_PER_L * maxFuel);
|
||||||
|
const rho = FUEL_DENSITY_KG_PER_L;
|
||||||
|
return Math.max(0, (startFuel + emptyWeightKg / rho) * Math.exp(-k * rho * distanceKm) - emptyWeightKg / rho);
|
||||||
|
}
|
||||||
|
|
||||||
// Mirrors lib/game/penalty.ts — the exact abandon penalty at a given game clock.
|
// Mirrors lib/game/penalty.ts — the exact abandon penalty at a given game clock.
|
||||||
function penaltyFor(reward: number, createdSimTime: number, deadlineSimTime: number, clockMs: number): number {
|
function penaltyFor(reward: number, createdSimTime: number, deadlineSimTime: number, clockMs: number): number {
|
||||||
const span = deadlineSimTime - createdSimTime;
|
const span = deadlineSimTime - createdSimTime;
|
||||||
@@ -33,6 +43,7 @@ interface StateBody {
|
|||||||
id: string; originIcao: string; destIcao: string; reward: number; cargoType: string; cargoCount: number;
|
id: string; originIcao: string; destIcao: string; reward: number; cargoType: string; cargoCount: number;
|
||||||
deadlineSimTime: number; status: 'open' | 'loaded' | 'delivered' | 'expired' | 'abandoned'; planeId: string | null; createdSimTime: number;
|
deadlineSimTime: number; status: 'open' | 'loaded' | 'delivered' | 'expired' | 'abandoned'; planeId: string | null; createdSimTime: number;
|
||||||
}>;
|
}>;
|
||||||
|
catalog: Array<{ model: string; burnPerKm: number; emptyWeightKg: number; maxFuel: number }>; // v0.16.0 weighted burn inputs
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getState(page: Page): Promise<StateBody> {
|
async function getState(page: Page): Promise<StateBody> {
|
||||||
@@ -42,8 +53,16 @@ async function getState(page: Page): Promise<StateBody> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// The e2e instance runs with FLIGHT_TEST_HOOKS=1 (docker-compose.yml) — the hook is live.
|
// The e2e instance runs with FLIGHT_TEST_HOOKS=1 (docker-compose.yml) — the hook is live.
|
||||||
async function createPackage(page: Page, from?: string, to?: string, deadlineOffsetMs?: number): Promise<StateBody['packages'][number]> {
|
// weightKg (v0.27.0) forces the package weight instead of the RNG draw, so flows that load
|
||||||
const res = await page.request.post('/api/test/create-package', { data: { originIcao: from, destIcao: to, deadlineOffsetMs } });
|
// several packages onto one plane stay under its payload deterministically.
|
||||||
|
async function createPackage(
|
||||||
|
page: Page,
|
||||||
|
from?: string,
|
||||||
|
to?: string,
|
||||||
|
deadlineOffsetMs?: number,
|
||||||
|
weightKg?: number,
|
||||||
|
): Promise<StateBody['packages'][number]> {
|
||||||
|
const res = await page.request.post('/api/test/create-package', { data: { originIcao: from, destIcao: to, deadlineOffsetMs, weightKg } });
|
||||||
expect(res.status()).toBe(201);
|
expect(res.status()).toBe(201);
|
||||||
return (await res.json()) as StateBody['packages'][number];
|
return (await res.json()) as StateBody['packages'][number];
|
||||||
}
|
}
|
||||||
@@ -55,8 +74,10 @@ async function postSim(page: Page, body: Record<string, unknown>): Promise<void>
|
|||||||
|
|
||||||
// Set the time scale and VERIFY from the response that it stuck — if something external ever
|
// Set the time scale and VERIFY from the response that it stuck — if something external ever
|
||||||
// resets the live instance's controls mid-test, fail loudly here instead of timing out later.
|
// resets the live instance's controls mid-test, fail loudly here instead of timing out later.
|
||||||
|
// ISS-041 also clears pause: a landing pauses the sim, so any fast-forward after one must
|
||||||
|
// resume it or the clock stays frozen and the next wait hangs.
|
||||||
async function setScale(page: Page, scale: number): Promise<void> {
|
async function setScale(page: Page, scale: number): Promise<void> {
|
||||||
const res = await page.request.post('/api/sim', { data: { timeScale: scale } });
|
const res = await page.request.post('/api/sim', { data: { timeScale: scale, paused: false } });
|
||||||
expect(res.status()).toBe(200);
|
expect(res.status()).toBe(200);
|
||||||
const body = (await res.json()) as { timeScale: number };
|
const body = (await res.json()) as { timeScale: number };
|
||||||
expect(body.timeScale, `timeScale should be ${scale} after POST /api/sim`).toBe(scale);
|
expect(body.timeScale, `timeScale should be ${scale} after POST /api/sim`).toBe(scale);
|
||||||
@@ -90,17 +111,26 @@ test.describe.configure({ mode: 'serial' }); // shared live DB — order matters
|
|||||||
// (repositioning needs no package — v0.12.0 manual flight), and abandon any leftover cargo so
|
// (repositioning needs no package — v0.12.0 manual flight), and abandon any leftover cargo so
|
||||||
// exact cash/rep assertions start from a clean baseline even after an interrupted previous run.
|
// exact cash/rep assertions start from a clean baseline even after an interrupted previous run.
|
||||||
async function flyHomeViaApi(page: Page): Promise<void> {
|
async function flyHomeViaApi(page: Page): Promise<void> {
|
||||||
const s0 = await getState(page);
|
let s = await getState(page);
|
||||||
const plane = s0.planes.find((p) => p.id === 'plane-starter')!;
|
let plane = s.planes.find((p) => p.id === 'plane-starter')!;
|
||||||
if (plane.status === 'flying' || plane.locationIcao !== HUB) {
|
if (plane.status === 'flying' || plane.locationIcao !== HUB) {
|
||||||
// Fast-forward any leftover leg / repositioning flight (~20 s real time worst case at 1000×).
|
// Fast-forward any leftover leg / repositioning flight (~20 s real time worst case at 1000×).
|
||||||
await setScale(page, SCALE);
|
await setScale(page, SCALE);
|
||||||
}
|
}
|
||||||
if (plane.status === 'flying') {
|
if (plane.status === 'flying') {
|
||||||
// Let the in-flight leg finish before repositioning.
|
// Let the in-flight leg finish before repositioning. While flying, locationIcao stays at the
|
||||||
|
// DEPARTURE airport, so the pre-landing snapshot can't tell us where the plane ends up — re-read
|
||||||
|
// state after landing before deciding whether a repositioning flight is needed (run #41 retry: a
|
||||||
|
// leftover EDDF→EDFH leg landed away from home but the helper still believed it was home and
|
||||||
|
// skipped the fly-home).
|
||||||
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.status), { timeout: 240_000 }).toBe('available');
|
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.status), { timeout: 240_000 }).toBe('available');
|
||||||
|
s = await getState(page);
|
||||||
|
plane = s.planes.find((p) => p.id === 'plane-starter')!;
|
||||||
}
|
}
|
||||||
if (plane.locationIcao !== HUB) {
|
if (plane.locationIcao !== HUB) {
|
||||||
|
// ISS-041: the landing above paused the sim — setScale clears pause so the return leg
|
||||||
|
// fast-forwards instead of taking real-time hours.
|
||||||
|
await setScale(page, SCALE);
|
||||||
const res = await page.request.post(`/api/planes/${plane.id}/fly`, { data: { destIcao: HUB } });
|
const res = await page.request.post(`/api/planes/${plane.id}/fly`, { data: { destIcao: HUB } });
|
||||||
expect(res.ok()).toBeTruthy(); // repositioning needs no package (v0.12.0 manual flight)
|
expect(res.ok()).toBeTruthy(); // repositioning needs no package (v0.12.0 manual flight)
|
||||||
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.locationIcao), { timeout: 240_000 }).toBe(HUB);
|
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.locationIcao), { timeout: 240_000 }).toBe(HUB);
|
||||||
@@ -133,6 +163,14 @@ test('full core loop via UI: load → fly to destination → exact reward + rep
|
|||||||
expect(pkg.originIcao).toBe(HUB);
|
expect(pkg.originIcao).toBe(HUB);
|
||||||
expect(pkg.destIcao).toBe(nearest.icao);
|
expect(pkg.destIcao).toBe(nearest.icao);
|
||||||
|
|
||||||
|
// Precondition (server truth) before clicking Load: the starter must be grounded at the package's
|
||||||
|
// origin — that is exactly what makes it load-eligible, and a stale pane snapshot can't prove it.
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const b = await getState(page);
|
||||||
|
const p = b.planes.find((x) => x.id === 'plane-starter')!;
|
||||||
|
return p.status === 'available' && p.locationIcao === pkg.originIcao;
|
||||||
|
}, { timeout: 30_000, message: 'waiting for plane-starter to be grounded at the package origin (self-heal incomplete?)' }).toBe(true);
|
||||||
|
|
||||||
// LOAD via the UI: exactly one eligible plane (the starter at EDDF) → direct button.
|
// LOAD via the UI: exactly one eligible plane (the starter at EDDF) → direct button.
|
||||||
await page.goto('/');
|
await page.goto('/');
|
||||||
const loadBtn = page.getByTestId(`load-${pkg.id}`);
|
const loadBtn = page.getByTestId(`load-${pkg.id}`);
|
||||||
@@ -149,10 +187,17 @@ test('full core loop via UI: load → fly to destination → exact reward + rep
|
|||||||
await expect(flyBtn).toBeEnabled();
|
await expect(flyBtn).toBeEnabled();
|
||||||
await flyBtn.click();
|
await flyBtn.click();
|
||||||
|
|
||||||
let s = await getState(page);
|
|
||||||
const planeId = 'plane-starter';
|
const planeId = 'plane-starter';
|
||||||
expect(s.planes.find((p) => p.id === planeId)!.status).toBe('flying');
|
// The click fires the fly POST asynchronously (runAction is fire-and-forget from the test's view),
|
||||||
expect(s.planes.find((p) => p.id === planeId)!.destIcao).toBe(nearest.icao);
|
// so a getState issued immediately can race ahead of it and still see 'available' — poll until the
|
||||||
|
// fly actually took effect on the server (the run #36/#41 flake).
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const b = await getState(page);
|
||||||
|
const p = b.planes.find((x) => x.id === planeId)!;
|
||||||
|
return p.status === 'flying' && p.destIcao === nearest.icao;
|
||||||
|
}, { timeout: 15_000, message: 'waiting for the fly click to take effect (status "flying" + dest set)' }).toBe(true);
|
||||||
|
|
||||||
|
let s = await getState(page);
|
||||||
|
|
||||||
// Fast-forward to arrival (a few seconds of real time at 1000×).
|
// Fast-forward to arrival (a few seconds of real time at 1000×).
|
||||||
await setScale(page, SCALE);
|
await setScale(page, SCALE);
|
||||||
@@ -174,8 +219,12 @@ test('full core loop via UI: load → fly to destination → exact reward + rep
|
|||||||
const repGain = Math.round((REP_BASE + REP_PER_KM * exactKm) * 100) / 100;
|
const repGain = Math.round((REP_BASE + REP_PER_KM * exactKm) * 100) / 100;
|
||||||
expect(s.account.reputation).toBeCloseTo(Math.round((before.account.reputation + repGain) * 100) / 100, 9);
|
expect(s.account.reputation).toBeCloseTo(Math.round((before.account.reputation + repGain) * 100) / 100, 9);
|
||||||
|
|
||||||
// Fuel burned exactly burnPerKm × km (analytic movement — no rounding drift).
|
// Fuel burned per the v0.16.0 weight-proportional model (closed form — no rounding drift).
|
||||||
expect(landed.fuel).toBeCloseTo(Math.max(0, before.planes.find((p) => p.id === planeId)!.fuel - BURN_PER_KM * exactKm), 6);
|
const entry = before.catalog.find((e) => e.model === 'atr72')!;
|
||||||
|
expect(landed.fuel).toBeCloseTo(
|
||||||
|
fuelAfter(before.planes.find((p) => p.id === planeId)!.fuel, entry.burnPerKm, entry.emptyWeightKg, entry.maxFuel, exactKm),
|
||||||
|
6,
|
||||||
|
);
|
||||||
|
|
||||||
// Refuel via the API: cost = (maxFuel − fuel) × FUEL_PRICE_PER_L, deducted exactly.
|
// Refuel via the API: cost = (maxFuel − fuel) × FUEL_PRICE_PER_L, deducted exactly.
|
||||||
const refuelRes = await page.request.post(`/api/planes/${planeId}/refuel`);
|
const refuelRes = await page.request.post(`/api/planes/${planeId}/refuel`);
|
||||||
@@ -186,7 +235,9 @@ test('full core loop via UI: load → fly to destination → exact reward + rep
|
|||||||
const refuelCost = Math.round((afterRefuel.maxFuel - landed.fuel) * FUEL_PRICE_PER_L * 100) / 100;
|
const refuelCost = Math.round((afterRefuel.maxFuel - landed.fuel) * FUEL_PRICE_PER_L * 100) / 100;
|
||||||
expect(s.account.cash).toBeCloseTo(before.account.cash + pkg.reward - refuelCost, 6);
|
expect(s.account.cash).toBeCloseTo(before.account.cash + pkg.reward - refuelCost, 6);
|
||||||
|
|
||||||
// Restore: fly home (repositioning — no package needed in the v0.12.0 model).
|
// Restore: fly home (repositioning — no package needed in the v0.12.0 model). ISS-041: the
|
||||||
|
// arrival above paused the sim, so re-set SCALE for the return leg (setScale clears pause).
|
||||||
|
await setScale(page, SCALE);
|
||||||
const homeRes = await page.request.post(`/api/planes/${planeId}/fly`, { data: { destIcao: HUB } });
|
const homeRes = await page.request.post(`/api/planes/${planeId}/fly`, { data: { destIcao: HUB } });
|
||||||
expect(homeRes.ok()).toBeTruthy();
|
expect(homeRes.ok()).toBeTruthy();
|
||||||
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === planeId)!.locationIcao), { timeout: 120_000 }).toBe(HUB);
|
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === planeId)!.locationIcao), { timeout: 120_000 }).toBe(HUB);
|
||||||
@@ -197,9 +248,10 @@ test('abandon while grounded deducts exactly the formula penalty', async ({ page
|
|||||||
await flyHomeViaApi(page);
|
await flyHomeViaApi(page);
|
||||||
const before = await getState(page);
|
const before = await getState(page);
|
||||||
|
|
||||||
// Two packages at the hub — load both, abandon one through the UI.
|
// Two packages at the hub — load both, abandon one through the UI. Forced weights keep
|
||||||
const pkgA = await createPackage(page, HUB, 'LEMD', 24 * 3_600_000);
|
// the pair under the starter's payload (v0.27.0) so both loads are deterministic.
|
||||||
const pkgB = await createPackage(page, HUB, 'LEMD', 24 * 3_600_000);
|
const pkgA = await createPackage(page, HUB, 'LEMD', 24 * 3_600_000, 1_000);
|
||||||
|
const pkgB = await createPackage(page, HUB, 'LEMD', 24 * 3_600_000, 1_000);
|
||||||
for (const p of [pkgA, pkgB]) {
|
for (const p of [pkgA, pkgB]) {
|
||||||
const res = await page.request.post(`/api/packages/${p.id}/load`, { data: { planeId: 'plane-starter' } });
|
const res = await page.request.post(`/api/packages/${p.id}/load`, { data: { planeId: 'plane-starter' } });
|
||||||
expect(res.ok()).toBeTruthy();
|
expect(res.ok()).toBeTruthy();
|
||||||
@@ -239,8 +291,8 @@ test('expired packages deliver and abandon with no reward and no penalty', async
|
|||||||
// destination differs from A's so it stays bound on the plane at LEMD arrival and can
|
// destination differs from A's so it stays bound on the plane at LEMD arrival and can
|
||||||
// still be abandoned (an expired package whose dest matches the arrival airport is
|
// still be abandoned (an expired package whose dest matches the arrival airport is
|
||||||
// unbound by the tick instead).
|
// unbound by the tick instead).
|
||||||
const pkgA = await createPackage(page, HUB, 'LEMD', 10_000); // short game-time deadline
|
const pkgA = await createPackage(page, HUB, 'LEMD', 10_000, 1_000); // short game-time deadline; forced weights keep the pair under payload (v0.27.0)
|
||||||
const pkgB = await createPackage(page, HUB, 'EHAM', 10_000);
|
const pkgB = await createPackage(page, HUB, 'EHAM', 10_000, 1_000);
|
||||||
for (const p of [pkgA, pkgB]) {
|
for (const p of [pkgA, pkgB]) {
|
||||||
const res = await page.request.post(`/api/packages/${p.id}/load`, { data: { planeId: 'plane-starter' } });
|
const res = await page.request.post(`/api/packages/${p.id}/load`, { data: { planeId: 'plane-starter' } });
|
||||||
expect(res.ok()).toBeTruthy();
|
expect(res.ok()).toBeTruthy();
|
||||||
@@ -273,8 +325,10 @@ test('expired packages deliver and abandon with no reward and no penalty', async
|
|||||||
expect(s.packages.find((p) => p.id === pkgB.id)!.status).toBe('abandoned');
|
expect(s.packages.find((p) => p.id === pkgB.id)!.status).toBe('abandoned');
|
||||||
expect(s.account.cash).toBe(cashBeforeAbandon); // free — expired abandons cost nothing
|
expect(s.account.cash).toBe(cashBeforeAbandon); // free — expired abandons cost nothing
|
||||||
|
|
||||||
// Restore: refuel + fly home (scale is still SCALE from the expiry wait above).
|
// Restore: refuel + fly home. ISS-041: the LEMD arrival above paused the sim, so
|
||||||
|
// re-set SCALE for the return leg (setScale clears pause; the expiry wait's scale is kept).
|
||||||
await page.request.post('/api/planes/plane-starter/refuel');
|
await page.request.post('/api/planes/plane-starter/refuel');
|
||||||
|
await setScale(page, SCALE);
|
||||||
const homeRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
const homeRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||||
expect(homeRes.ok()).toBeTruthy();
|
expect(homeRes.ok()).toBeTruthy();
|
||||||
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.locationIcao), { timeout: 240_000 }).toBe(HUB);
|
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.locationIcao), { timeout: 240_000 }).toBe(HUB);
|
||||||
@@ -312,17 +366,21 @@ test('load and fly validation paths (404 / 409 / 400)', async ({ page }) => {
|
|||||||
res = await page.request.post(`/api/packages/${pkg.id}/abandon`);
|
res = await page.request.post(`/api/packages/${pkg.id}/abandon`);
|
||||||
expect(res.status()).toBe(409);
|
expect(res.status()).toBe(409);
|
||||||
|
|
||||||
// Fly home from the hop so the fuel section starts at the hub.
|
// Fly home from the hop so the fuel section starts at the hub. ISS-041: the hop arrival above
|
||||||
|
// paused the sim, so re-set SCALE for this leg (setScale clears pause).
|
||||||
|
await setScale(page, SCALE);
|
||||||
res = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
res = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||||
expect(res.ok()).toBeTruthy();
|
expect(res.ok()).toBeTruthy();
|
||||||
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.locationIcao), { timeout: 120_000 }).toBe(HUB);
|
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.locationIcao), { timeout: 120_000 }).toBe(HUB);
|
||||||
|
|
||||||
// Insufficient fuel: a full-tank one-way burn of > half the tank makes the return leg unfuelable.
|
// Insufficient fuel (v0.16.0 weighted burn): a full tank covers the FAR round trip —
|
||||||
|
// the plane gets lighter as fuel burns off, so both legs fit — but landing back at the
|
||||||
|
// hub leaves too little for ANOTHER long leg: the second outbound must 409.
|
||||||
const s0 = await getState(page);
|
const s0 = await getState(page);
|
||||||
const starter = s0.planes.find((p) => p.id === 'plane-starter')!;
|
const starter = s0.planes.find((p) => p.id === 'plane-starter')!;
|
||||||
expect(starter.locationIcao).toBe(HUB); // landed back at the hub from the hop above
|
expect(starter.locationIcao).toBe(HUB); // landed back at the hub from the hop above
|
||||||
if (starter.fuel < starter.maxFuel) {
|
if (starter.fuel < starter.maxFuel) {
|
||||||
await page.request.post('/api/planes/plane-starter/refuel'); // ensure a full tank for the long leg
|
await page.request.post('/api/planes/plane-starter/refuel'); // ensure a full tank for the long legs
|
||||||
}
|
}
|
||||||
const farRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: FAR } });
|
const farRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: FAR } });
|
||||||
expect(farRes.ok()).toBeTruthy();
|
expect(farRes.ok()).toBeTruthy();
|
||||||
@@ -332,16 +390,20 @@ test('load and fly validation paths (404 / 409 / 400)', async ({ page }) => {
|
|||||||
const sFar = await getState(page);
|
const sFar = await getState(page);
|
||||||
const atFar = sFar.planes.find((p) => p.id === 'plane-starter')!;
|
const atFar = sFar.planes.find((p) => p.id === 'plane-starter')!;
|
||||||
expect(atFar.locationIcao).toBe(FAR);
|
expect(atFar.locationIcao).toBe(FAR);
|
||||||
// The return leg needs the same burn as the outbound — more than what's left.
|
// The return leg fits: the weighted burn over it is less than what's left in the tank.
|
||||||
|
// ISS-041: the FAR arrival above paused the sim, so re-set SCALE for this leg (setScale clears pause).
|
||||||
|
await setScale(page, SCALE);
|
||||||
const backRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
const backRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||||
expect(backRes.status()).toBe(409);
|
expect(backRes.ok()).toBeTruthy();
|
||||||
expect(((await backRes.json()) as { error: string }).error).toMatch(/insufficient fuel/i);
|
|
||||||
|
|
||||||
// Restore: refuel + fly home.
|
|
||||||
await page.request.post('/api/planes/plane-starter/refuel');
|
|
||||||
const homeRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
|
||||||
expect(homeRes.ok()).toBeTruthy();
|
|
||||||
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.locationIcao), { timeout: 240_000 }).toBe(HUB);
|
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.locationIcao), { timeout: 240_000 }).toBe(HUB);
|
||||||
|
|
||||||
|
// …but the tank is now too light for another FAR leg.
|
||||||
|
const againFar = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: FAR } });
|
||||||
|
expect(againFar.status()).toBe(409);
|
||||||
|
expect(((await againFar.json()) as { error: string }).error).toMatch(/insufficient fuel/i);
|
||||||
|
|
||||||
|
// Restore: refuel (the plane is already home).
|
||||||
|
await page.request.post('/api/planes/plane-starter/refuel');
|
||||||
});
|
});
|
||||||
|
|
||||||
// Great-circle distance in km — mirrors lib/geo.ts (same formula, same R).
|
// Great-circle distance in km — mirrors lib/geo.ts (same formula, same R).
|
||||||
|
|||||||
+4
-1
@@ -13,7 +13,7 @@ test('GET /api/version returns the app version from package.json', async ({ page
|
|||||||
expect(body.version).toBe(pkg.version);
|
expect(body.version).toBe(pkg.version);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('GET /api/openapi serves the spec with all ten endpoints and the package.json version', async ({ page }) => {
|
test('GET /api/openapi serves the spec with all thirteen endpoints and the package.json version', async ({ page }) => {
|
||||||
const res = await page.request.get('/api/openapi');
|
const res = await page.request.get('/api/openapi');
|
||||||
expect(res.status()).toBe(200);
|
expect(res.status()).toBe(200);
|
||||||
expect(res.headers()['content-type']).toContain('application/json');
|
expect(res.headers()['content-type']).toContain('application/json');
|
||||||
@@ -26,8 +26,11 @@ test('GET /api/openapi serves the spec with all ten endpoints and the package.js
|
|||||||
'/api/market/buy-plane',
|
'/api/market/buy-plane',
|
||||||
'/api/market/sell-plane',
|
'/api/market/sell-plane',
|
||||||
'/api/packages/{id}/abandon',
|
'/api/packages/{id}/abandon',
|
||||||
|
'/api/packages/{id}/ignore', // v0.29.0 (ISS-047 part B)
|
||||||
'/api/packages/{id}/load',
|
'/api/packages/{id}/load',
|
||||||
'/api/planes/{planeId}/fly',
|
'/api/planes/{planeId}/fly',
|
||||||
|
'/api/planes/{planeId}/queue',
|
||||||
|
'/api/planes/{planeId}/queue/cancel',
|
||||||
'/api/planes/{planeId}/refuel',
|
'/api/planes/{planeId}/refuel',
|
||||||
'/api/sim',
|
'/api/sim',
|
||||||
'/api/state',
|
'/api/state',
|
||||||
|
|||||||
+295
-4
@@ -6,6 +6,10 @@ import { test, expect, type Page } from '@playwright/test';
|
|||||||
// highlight layers (planes-highlight / routes-highlight / airports-highlight), each filtered
|
// highlight layers (planes-highlight / routes-highlight / airports-highlight), each filtered
|
||||||
// to match nothing until a hover sets the filter — asserted here via window.__flightMap's
|
// to match nothing until a hover sets the filter — asserted here via window.__flightMap's
|
||||||
// queryRenderedFeatures, same pattern as e2e/map.spec.ts and e2e/map-interactions.spec.ts.
|
// queryRenderedFeatures, same pattern as e2e/map.spec.ts and e2e/map-interactions.spec.ts.
|
||||||
|
// ISS-022/025/027 (v0.22.0): any hover carrying two endpoints ALSO draws the full great-circle
|
||||||
|
// trace between them in a fourth top-most layer (`hover-route`, dashed) — job-list rows, on-board
|
||||||
|
// cargo rows and the Relocate section; the relocate preview rings only its TARGET airport, which
|
||||||
|
// additionally gets a distinct green ring in `airports-target-highlight` (ISS-022).
|
||||||
|
|
||||||
const SCALE = 1000; // fastest sim speed (v0.14.0 ladder top) — keeps flights to seconds of real time
|
const SCALE = 1000; // fastest sim speed (v0.14.0 ladder top) — keeps flights to seconds of real time
|
||||||
const HUB = 'EDDF'; // must match HUB_ICAO in lib/game/seed.ts
|
const HUB = 'EDDF'; // must match HUB_ICAO in lib/game/seed.ts
|
||||||
@@ -20,6 +24,8 @@ interface PlaneState {
|
|||||||
maxFuel: number;
|
maxFuel: number;
|
||||||
locationIcao: string;
|
locationIcao: string;
|
||||||
destIcao: string | null;
|
destIcao: string | null;
|
||||||
|
lat: number; // live position — interpolated per snapshot while flying, airport coords when grounded
|
||||||
|
lon: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface PackageState {
|
interface PackageState {
|
||||||
@@ -49,9 +55,10 @@ async function postSim(page: Page, body: unknown) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Set the time scale and VERIFY from the response that it stuck — a silent reset would
|
// Set the time scale and VERIFY from the response that it stuck — a silent reset would
|
||||||
// otherwise surface as an unexplained landing-wait timeout.
|
// otherwise surface as an unexplained landing-wait timeout. ISS-041 also clears pause: a
|
||||||
|
// landing pauses the sim, so any fast-forward after one must resume it or the clock stays frozen.
|
||||||
async function setScale(page: Page, scale: number): Promise<void> {
|
async function setScale(page: Page, scale: number): Promise<void> {
|
||||||
const res = await page.request.post('/api/sim', { data: { timeScale: scale } });
|
const res = await page.request.post('/api/sim', { data: { timeScale: scale, paused: false } });
|
||||||
expect(res.status()).toBe(200);
|
expect(res.status()).toBe(200);
|
||||||
const body = (await res.json()) as { timeScale: number };
|
const body = (await res.json()) as { timeScale: number };
|
||||||
expect(body.timeScale, `timeScale should be ${scale} after POST /api/sim`).toBe(scale);
|
expect(body.timeScale, `timeScale should be ${scale} after POST /api/sim`).toBe(scale);
|
||||||
@@ -89,6 +96,9 @@ async function flyHomeViaApi(page: Page): Promise<void> {
|
|||||||
.toBe(true);
|
.toBe(true);
|
||||||
}
|
}
|
||||||
if (starter.locationIcao !== HUB) {
|
if (starter.locationIcao !== HUB) {
|
||||||
|
// ISS-041: the landing above paused the sim — setScale clears pause so the return leg
|
||||||
|
// fast-forwards instead of taking real-time hours.
|
||||||
|
await setScale(page, SCALE);
|
||||||
const res = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
const res = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||||
expect(res.status()).toBe(200); // repositioning needs no package (v0.12.0 manual flight)
|
expect(res.status()).toBe(200); // repositioning needs no package (v0.12.0 manual flight)
|
||||||
await expect
|
await expect
|
||||||
@@ -110,12 +120,30 @@ async function waitForAirportCount(page: Page): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Rendered features of the given layers in the current viewport, [] until the map exists.
|
// Rendered features of the given layers in the current viewport, [] until the map exists.
|
||||||
function renderedFeatures(page: Page, layers: string[]) {
|
function renderedFeatures(
|
||||||
|
page: Page,
|
||||||
|
layers: string[],
|
||||||
|
): Promise<Array<{ type?: unknown; id?: unknown; properties?: unknown; geometry?: unknown }>> {
|
||||||
return page.evaluate((ls: string[]) => {
|
return page.evaluate((ls: string[]) => {
|
||||||
const m = (window as any).__flightMap;
|
const m = (window as any).__flightMap;
|
||||||
if (!m) return [];
|
if (!m) return [];
|
||||||
try {
|
try {
|
||||||
return m.queryRenderedFeatures(undefined, { layers: ls });
|
// queryRenderedFeatures returns live GeoJSONFeature instances whose `geometry` is a lazy
|
||||||
|
// PROTOTYPE getter — Playwright's evaluate serialization copies only own enumerable props,
|
||||||
|
// so geometry silently vanishes across the page boundary (CI runs #69–#71: strict-equality
|
||||||
|
// timeouts → TypeError on f.geometry.coordinates → filter-found-nothing timeouts). Map to
|
||||||
|
// plain objects IN-PAGE so the getter is evaluated before serialization.
|
||||||
|
return (m.queryRenderedFeatures(undefined, { layers: ls }) as Array<{
|
||||||
|
type?: unknown;
|
||||||
|
id?: unknown;
|
||||||
|
properties?: unknown;
|
||||||
|
geometry?: unknown;
|
||||||
|
}>).map((f) => ({
|
||||||
|
type: f.type,
|
||||||
|
id: f.id,
|
||||||
|
properties: f.properties,
|
||||||
|
geometry: f.geometry,
|
||||||
|
}));
|
||||||
} catch {
|
} catch {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
@@ -157,6 +185,56 @@ async function fitToAirports(page: Page, icaos: string[]): Promise<void> {
|
|||||||
await page.waitForTimeout(300);
|
await page.waitForTimeout(300);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// [lon, lat] of an airport from the same /api/airports dataset the map draws its traces from.
|
||||||
|
async function airportLonLat(page: Page, icao: string): Promise<[number, number]> {
|
||||||
|
const fc = (await (await page.request.get('/api/airports')).json()) as {
|
||||||
|
features: Array<{ properties: { icao: string; lat: number; lon: number } }>;
|
||||||
|
};
|
||||||
|
const f = fc.features.find((x) => x.properties.icao === icao);
|
||||||
|
if (!f) throw new Error(`airport ${icao} not found in /api/airports`);
|
||||||
|
return [f.properties.lon, f.properties.lat];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ISS-022/025/027: the hover-route layer must hold the great-circle trace from origin to dest.
|
||||||
|
// MapLibre stores GeoJSON geometry in per-tile INTEGER grids and clips long lines across tiles, so
|
||||||
|
// queryRenderedFeatures returns ONE FEATURE PER TILE the line crosses (the 1420 km EDDF→LEMD leg is
|
||||||
|
// 4 segments at z=4 / 5 at z=5) with coordinates quantized to the rendered zoom's grid — up to ~half
|
||||||
|
// a grid step off (~0.001° observed at z≥4, ~0.02° worst case at z=0). A strict single-feature +
|
||||||
|
// exact-coords comparison can therefore never match even when the line is drawn correctly (CI run #69:
|
||||||
|
// all three hover-route timeouts while the trace was visibly rendered), so we accept any number of
|
||||||
|
// segments and require some segment to START within EPS of `from` and some to END within EPS of `to`.
|
||||||
|
// The true endpoints survive clipping verbatim in whichever tile contains them. (CI runs #69–#71:
|
||||||
|
// features could arrive WITHOUT a usable geometry because Playwright's evaluate serialization drops
|
||||||
|
// the lazy prototype getter — not MapLibre artifacts; renderedFeatures now maps to plain objects
|
||||||
|
// in-page.) The helper still filters to real LineString segments and treats "none yet" as keep-polling
|
||||||
|
// instead of throwing inside the poll callback. Call fitToAirports([from, to]) first — rendered
|
||||||
|
// features are viewport-scoped.
|
||||||
|
const HOVER_ROUTE_EPS_DEG = 0.05; // ~5 km: above worst-case quantization at any zoom, below the distance between any two EU airports
|
||||||
|
|
||||||
|
async function expectHoverRoute(page: Page, fromIcao: string, toIcao: string): Promise<void> {
|
||||||
|
const [from, to] = await Promise.all([airportLonLat(page, fromIcao), airportLonLat(page, toIcao)]);
|
||||||
|
const near = (a: [number, number], b: [number, number]) =>
|
||||||
|
Math.abs(a[0] - b[0]) <= HOVER_ROUTE_EPS_DEG && Math.abs(a[1] - b[1]) <= HOVER_ROUTE_EPS_DEG;
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const feats = (await renderedFeatures(page, ['hover-route'])) as Array<{ geometry?: { type: string; coordinates: [number, number][] } }>;
|
||||||
|
// Features are plain objects with in-page-evaluated geometry (see renderedFeatures). The filter
|
||||||
|
// guards against degenerate/zero-length clipped segments and keeps this poll callback total — a
|
||||||
|
// throw inside expect.poll fails the test instantly instead of retrying. "None yet" → keep polling.
|
||||||
|
const segs = feats.filter(
|
||||||
|
(f): f is { geometry: { type: 'LineString'; coordinates: [number, number][] } } =>
|
||||||
|
!!f.geometry && f.geometry.type === 'LineString' && Array.isArray(f.geometry.coordinates) && f.geometry.coordinates.length >= 2,
|
||||||
|
);
|
||||||
|
if (!segs.length) return false;
|
||||||
|
// The line may be clipped into several per-tile segments — check the endpoints across all of them.
|
||||||
|
const startsAtFrom = segs.some((f) => near(f.geometry.coordinates[0], from));
|
||||||
|
const endsAtTo = segs.some((f) => {
|
||||||
|
const c = f.geometry.coordinates;
|
||||||
|
return near(c[c.length - 1], to);
|
||||||
|
});
|
||||||
|
return startsAtFrom && endsAtTo;
|
||||||
|
}, { timeout: 15_000, message: `waiting for the hover-route line ${fromIcao} → ${toIcao}` }).toBe(true);
|
||||||
|
}
|
||||||
|
|
||||||
test('hovering a fleet row highlights the plane on the map', async ({ page }) => {
|
test('hovering a fleet row highlights the plane on the map', async ({ page }) => {
|
||||||
test.setTimeout(300_000); // self-heal can take minutes after an interrupted run
|
test.setTimeout(300_000); // self-heal can take minutes after an interrupted run
|
||||||
await flyHomeViaApi(page); // deterministic: the starter sits at EDDF, inside the initial view
|
await flyHomeViaApi(page); // deterministic: the starter sits at EDDF, inside the initial view
|
||||||
@@ -227,6 +305,7 @@ test('hovering an open package highlights its endpoint airports', async ({ page
|
|||||||
await fitToAirports(page, [HUB, DEST]);
|
await fitToAirports(page, [HUB, DEST]);
|
||||||
|
|
||||||
expect(await renderedFeatures(page, ['airports-highlight'])).toHaveLength(0);
|
expect(await renderedFeatures(page, ['airports-highlight'])).toHaveLength(0);
|
||||||
|
expect(await renderedFeatures(page, ['airports-target-highlight'])).toHaveLength(0);
|
||||||
|
|
||||||
await row.hover();
|
await row.hover();
|
||||||
await expect.poll(async () => {
|
await expect.poll(async () => {
|
||||||
@@ -235,11 +314,129 @@ test('hovering an open package highlights its endpoint airports', async ({ page
|
|||||||
}, { timeout: 15_000, message: 'waiting for the airports-highlight layer to show both endpoints' })
|
}, { timeout: 15_000, message: 'waiting for the airports-highlight layer to show both endpoints' })
|
||||||
.toBe(JSON.stringify([HUB, DEST].sort()));
|
.toBe(JSON.stringify([HUB, DEST].sort()));
|
||||||
|
|
||||||
|
// ISS-022 (v0.22.0): the ENTIRE trace is drawn too — a great-circle line from origin to dest,
|
||||||
|
// not just the endpoint rings.
|
||||||
|
await expectHoverRoute(page, HUB, DEST);
|
||||||
|
|
||||||
|
// And the TARGET airport gets its own distinct-colored ring — only the destination, never the origin.
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const feats = (await renderedFeatures(page, ['airports-target-highlight'])) as Array<{ properties: Record<string, unknown> }>;
|
||||||
|
return JSON.stringify(feats.map((f) => f.properties.icao).sort());
|
||||||
|
}, { timeout: 15_000, message: 'waiting for the airports-target-highlight layer to ring only the destination' })
|
||||||
|
.toBe(JSON.stringify([DEST]));
|
||||||
|
|
||||||
await unhover(page);
|
await unhover(page);
|
||||||
await expect.poll(async () => (await renderedFeatures(page, ['airports-highlight'])).length, {
|
await expect.poll(async () => (await renderedFeatures(page, ['airports-highlight'])).length, {
|
||||||
timeout: 15_000,
|
timeout: 15_000,
|
||||||
message: 'waiting for the highlight to clear after mouseleave',
|
message: 'waiting for the highlight to clear after mouseleave',
|
||||||
}).toBe(0);
|
}).toBe(0);
|
||||||
|
await expect.poll(async () => (await renderedFeatures(page, ['hover-route'])).length, {
|
||||||
|
timeout: 15_000,
|
||||||
|
message: 'waiting for the hover route trace to clear after mouseleave',
|
||||||
|
}).toBe(0);
|
||||||
|
await expect.poll(async () => (await renderedFeatures(page, ['airports-target-highlight'])).length, {
|
||||||
|
timeout: 15_000,
|
||||||
|
message: 'waiting for the target ring to clear after mouseleave',
|
||||||
|
}).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('hovering an on-board cargo row draws its trace and keeps the plane halo', async ({ page }) => {
|
||||||
|
test.setTimeout(300_000); // self-heal can take minutes after an interrupted run
|
||||||
|
await flyHomeViaApi(page); // deterministic: the starter sits grounded at EDDF
|
||||||
|
|
||||||
|
// Load a package onto the grounded starter so it shows up in the On board section.
|
||||||
|
const pkg = await createPackage(page, HUB, DEST);
|
||||||
|
const load = await page.request.post(`/api/packages/${pkg.id}/load`, { data: { planeId: 'plane-starter' } });
|
||||||
|
expect(load.status()).toBe(200);
|
||||||
|
|
||||||
|
await page.goto('/');
|
||||||
|
await waitForAirportCount(page);
|
||||||
|
|
||||||
|
const row = page.locator(`[data-testid="onboard-package-${pkg.id}"]`);
|
||||||
|
await expect(row, 'the loaded package appears in the On board section').toBeVisible({ timeout: 15_000 });
|
||||||
|
|
||||||
|
// Both endpoints must be in-viewport for queryRenderedFeatures to see the trace.
|
||||||
|
await fitToAirports(page, [HUB, DEST]);
|
||||||
|
|
||||||
|
await row.hover();
|
||||||
|
// ISS-025 (v0.22.0): same full origin→dest trace as job-list rows…
|
||||||
|
await expectHoverRoute(page, HUB, DEST);
|
||||||
|
// …and the package's plane keeps its halo lit (the hover carries planeId).
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const feats = (await renderedFeatures(page, ['planes-highlight'])) as Array<{ properties: Record<string, unknown> }>;
|
||||||
|
return feats.length > 0 && feats[0].properties.id === 'plane-starter';
|
||||||
|
}, { timeout: 15_000, message: 'waiting for the planes-highlight layer to show plane-starter' }).toBe(true);
|
||||||
|
|
||||||
|
await unhover(page);
|
||||||
|
await expect.poll(async () => (await renderedFeatures(page, ['hover-route'])).length, {
|
||||||
|
timeout: 15_000,
|
||||||
|
message: 'waiting for the hover route trace to clear after mouseleave',
|
||||||
|
}).toBe(0);
|
||||||
|
await expect.poll(async () => (await renderedFeatures(page, ['planes-highlight'])).length, {
|
||||||
|
timeout: 15_000,
|
||||||
|
message: 'waiting for the highlight to clear after mouseleave',
|
||||||
|
}).toBe(0);
|
||||||
|
|
||||||
|
// Leave the instance clean: abandon the loaded package so later specs start with an empty starter.
|
||||||
|
const res = await page.request.post(`/api/packages/${pkg.id}/abandon`);
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('hovering the Relocate section previews the planned route and target airport', async ({ page }) => {
|
||||||
|
test.setTimeout(300_000); // self-heal can take minutes after an interrupted run
|
||||||
|
await flyHomeViaApi(page); // deterministic: the starter sits grounded at EDDF
|
||||||
|
|
||||||
|
await page.goto('/');
|
||||||
|
await waitForAirportCount(page);
|
||||||
|
|
||||||
|
const section = page.getByTestId('relocate-section');
|
||||||
|
await expect(section, 'the Relocate section is visible').toBeVisible({ timeout: 15_000 });
|
||||||
|
|
||||||
|
// LeftPane fetches /api/airports on its own (separate from the map header count) — wait for
|
||||||
|
// the destination options to populate before selecting.
|
||||||
|
await expect(page.getByTestId('relocate-dest').locator(`option[value="${DEST}"]`)).toHaveCount(1, { timeout: 15_000 });
|
||||||
|
|
||||||
|
// Pick the starter + a known destination explicitly (the effective-selection defaults already do this).
|
||||||
|
await page.getByTestId('relocate-plane').selectOption('plane-starter');
|
||||||
|
await page.getByTestId('relocate-dest').selectOption(DEST);
|
||||||
|
|
||||||
|
// Both endpoints must be in-viewport for queryRenderedFeatures to see the trace.
|
||||||
|
await fitToAirports(page, [HUB, DEST]);
|
||||||
|
|
||||||
|
expect(await renderedFeatures(page, ['hover-route'])).toHaveLength(0);
|
||||||
|
expect(await renderedFeatures(page, ['airports-highlight'])).toHaveLength(0);
|
||||||
|
expect(await renderedFeatures(page, ['airports-target-highlight'])).toHaveLength(0);
|
||||||
|
|
||||||
|
// ISS-027 (v0.22.0): hovering the panel with a plane + destination selected previews the flight —
|
||||||
|
// dashed trace from the plane's airport to the destination…
|
||||||
|
await section.hover();
|
||||||
|
await expectHoverRoute(page, HUB, DEST);
|
||||||
|
// …and rings ONLY the target airport (the origin stays unmarked).
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const feats = (await renderedFeatures(page, ['airports-highlight'])) as Array<{ properties: Record<string, unknown> }>;
|
||||||
|
return JSON.stringify(feats.map((f) => f.properties.icao).sort());
|
||||||
|
}, { timeout: 15_000, message: 'waiting for the airports-highlight layer to ring only the target' })
|
||||||
|
.toBe(JSON.stringify([DEST]));
|
||||||
|
// …plus the destination's own distinct-colored ring (ISS-022) — same single icao.
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const feats = (await renderedFeatures(page, ['airports-target-highlight'])) as Array<{ properties: Record<string, unknown> }>;
|
||||||
|
return JSON.stringify(feats.map((f) => f.properties.icao).sort());
|
||||||
|
}, { timeout: 15_000, message: 'waiting for the airports-target-highlight layer to ring only the target' })
|
||||||
|
.toBe(JSON.stringify([DEST]));
|
||||||
|
|
||||||
|
await unhover(page);
|
||||||
|
await expect.poll(async () => (await renderedFeatures(page, ['hover-route'])).length, {
|
||||||
|
timeout: 15_000,
|
||||||
|
message: 'waiting for the hover route trace to clear after mouseleave',
|
||||||
|
}).toBe(0);
|
||||||
|
await expect.poll(async () => (await renderedFeatures(page, ['airports-highlight'])).length, {
|
||||||
|
timeout: 15_000,
|
||||||
|
message: 'waiting for the highlight to clear after mouseleave',
|
||||||
|
}).toBe(0);
|
||||||
|
await expect.poll(async () => (await renderedFeatures(page, ['airports-target-highlight'])).length, {
|
||||||
|
timeout: 15_000,
|
||||||
|
message: 'waiting for the target ring to clear after mouseleave',
|
||||||
|
}).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('hovering an on-board block of a flying plane highlights its route', async ({ page }) => {
|
test('hovering an on-board block of a flying plane highlights its route', async ({ page }) => {
|
||||||
@@ -291,6 +488,100 @@ test('hovering an on-board block of a flying plane highlights its route', async
|
|||||||
}, { timeout: 120_000, message: `waiting for plane-starter to land at ${DEST}` })
|
}, { timeout: 120_000, message: `waiting for plane-starter to land at ${DEST}` })
|
||||||
.toBe(true);
|
.toBe(true);
|
||||||
|
|
||||||
|
// ISS-041: the arrival above paused the sim, so re-set SCALE for this leg (setScale clears pause).
|
||||||
|
await setScale(page, SCALE);
|
||||||
|
const home = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||||
|
expect(home.status()).toBe(200);
|
||||||
|
await expect
|
||||||
|
.poll(async () => (await getState(page)).planes.find((p) => p.id === 'plane-starter')?.locationIcao === HUB, {
|
||||||
|
timeout: 120_000,
|
||||||
|
message: 'waiting for plane-starter to land back at the hub',
|
||||||
|
})
|
||||||
|
.toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('hovering an on-board package while its carrier is mid-flight traces from current position', async ({ page }) => {
|
||||||
|
test.setTimeout(600_000); // self-heal + one flight at scale 1000 + fly-home cleanup
|
||||||
|
await flyHomeViaApi(page);
|
||||||
|
|
||||||
|
// Full tank before departure — the EDDF↔LEMD round trip burns ~4970 L of the 6300 L tank.
|
||||||
|
const refuel = await page.request.post('/api/planes/plane-starter/refuel');
|
||||||
|
expect(refuel.status()).toBe(200);
|
||||||
|
|
||||||
|
await page.goto('/');
|
||||||
|
await waitForAirportCount(page);
|
||||||
|
|
||||||
|
// Load + fly via the API (same pattern as e2e/map-interactions.spec.ts), then speed up.
|
||||||
|
const pkg = await createPackage(page, HUB, DEST);
|
||||||
|
const load = await page.request.post(`/api/packages/${pkg.id}/load`, { data: { planeId: 'plane-starter' } });
|
||||||
|
expect(load.status()).toBe(200);
|
||||||
|
const fly = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: DEST } });
|
||||||
|
expect(fly.status()).toBe(200);
|
||||||
|
await setScale(page, SCALE);
|
||||||
|
|
||||||
|
// Wait until the starter is GENUINELY mid-flight — its live position clearly away from EDDF in
|
||||||
|
// both axes (well past HOVER_ROUTE_EPS_DEG) so "the trace starts at the plane" and "it starts at
|
||||||
|
// the pickup airport" are distinguishable. The ~10 s leg at scale 1000 gives a wide window.
|
||||||
|
const hubLonLat = await airportLonLat(page, HUB);
|
||||||
|
await expect
|
||||||
|
.poll(async () => {
|
||||||
|
const p = (await getState(page)).planes.find((x) => x.id === 'plane-starter');
|
||||||
|
if (!p || p.status !== 'flying') return false;
|
||||||
|
return Math.abs(p.lon - hubLonLat[0]) > 0.2 && Math.abs(p.lat - hubLonLat[1]) > 0.2;
|
||||||
|
}, { timeout: 60_000, message: 'waiting for plane-starter to be clearly away from the hub' })
|
||||||
|
.toBe(true);
|
||||||
|
|
||||||
|
// Freeze mid-flight so the position is stable while we assert (same pause pattern as the
|
||||||
|
// flying-plane hover test above): paused, every /api/state snapshot reports the same lat/lon.
|
||||||
|
await postSim(page, { paused: true });
|
||||||
|
|
||||||
|
const row = page.locator(`[data-testid="onboard-package-${pkg.id}"]`);
|
||||||
|
await expect(row, 'the loaded package appears in the On board section').toBeVisible({ timeout: 15_000 });
|
||||||
|
|
||||||
|
// Both endpoints must be in-viewport for queryRenderedFeatures to see the trace.
|
||||||
|
await fitToAirports(page, [HUB, DEST]);
|
||||||
|
|
||||||
|
const live = (await getState(page)).planes.find((x) => x.id === 'plane-starter')!;
|
||||||
|
const liveLonLat: [number, number] = [live.lon, live.lat]; // stable — the sim is paused
|
||||||
|
const destLonLat = await airportLonLat(page, DEST);
|
||||||
|
|
||||||
|
await row.hover();
|
||||||
|
// ISS-040 (v0.23.2): the trace starts at the carrier's LIVE position and ends at the destination,
|
||||||
|
// and NO segment may start near the pickup airport (the old origin-based behavior). Same per-tile
|
||||||
|
// clipping/quantization caveats as expectHoverRoute — check endpoints across all segments with EPS.
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const feats = (await renderedFeatures(page, ['hover-route'])) as Array<{ geometry?: { type: string; coordinates: [number, number][] } }>;
|
||||||
|
const segs = feats.filter(
|
||||||
|
(f): f is { geometry: { type: 'LineString'; coordinates: [number, number][] } } =>
|
||||||
|
!!f.geometry && f.geometry.type === 'LineString' && Array.isArray(f.geometry.coordinates) && f.geometry.coordinates.length >= 2,
|
||||||
|
);
|
||||||
|
if (!segs.length) return false;
|
||||||
|
const near = (a: [number, number], b: [number, number]) =>
|
||||||
|
Math.abs(a[0] - b[0]) <= HOVER_ROUTE_EPS_DEG && Math.abs(a[1] - b[1]) <= HOVER_ROUTE_EPS_DEG;
|
||||||
|
const startsAtLive = segs.some((f) => near(f.geometry.coordinates[0], liveLonLat));
|
||||||
|
const endsAtDest = segs.some((f) => near(f.geometry.coordinates[f.geometry.coordinates.length - 1], destLonLat));
|
||||||
|
const noneStartsAtHub = !segs.some((f) => near(f.geometry.coordinates[0], hubLonLat));
|
||||||
|
return startsAtLive && endsAtDest && noneStartsAtHub;
|
||||||
|
}, { timeout: 15_000, message: 'waiting for the hover-route trace to run from the live position to the destination' }).toBe(true);
|
||||||
|
|
||||||
|
await unhover(page);
|
||||||
|
await expect.poll(async () => (await renderedFeatures(page, ['hover-route'])).length, {
|
||||||
|
timeout: 15_000,
|
||||||
|
message: 'waiting for the hover route trace to clear after mouseleave',
|
||||||
|
}).toBe(0);
|
||||||
|
|
||||||
|
// Resume and fast-forward to arrival — landing at DEST auto-delivers the package (v0.12.0), so
|
||||||
|
// flying home afterwards leaves the starter clean for the other specs.
|
||||||
|
await postSim(page, { timeScale: SCALE, paused: false });
|
||||||
|
await expect
|
||||||
|
.poll(async () => {
|
||||||
|
const p = (await getState(page)).planes.find((x) => x.id === 'plane-starter');
|
||||||
|
return !!p && p.status === 'available' && p.locationIcao === DEST;
|
||||||
|
}, { timeout: 120_000, message: `waiting for plane-starter to land at ${DEST}` })
|
||||||
|
.toBe(true);
|
||||||
|
|
||||||
|
// ISS-041: the arrival above paused the sim, so re-set SCALE for this leg (setScale clears pause).
|
||||||
|
await setScale(page, SCALE);
|
||||||
const home = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
const home = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||||
expect(home.status()).toBe(200);
|
expect(home.status()).toBe(200);
|
||||||
await expect
|
await expect
|
||||||
|
|||||||
@@ -69,9 +69,10 @@ async function postSim(page: Page, body: unknown) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Set the time scale and VERIFY from the response that it stuck — a silent reset would
|
// Set the time scale and VERIFY from the response that it stuck — a silent reset would
|
||||||
// otherwise surface as an unexplained landing-wait timeout.
|
// otherwise surface as an unexplained landing-wait timeout. ISS-041 also clears pause: a
|
||||||
|
// landing pauses the sim, so any fast-forward after one must resume it or the clock stays frozen.
|
||||||
async function setScale(page: Page, scale: number): Promise<void> {
|
async function setScale(page: Page, scale: number): Promise<void> {
|
||||||
const res = await page.request.post('/api/sim', { data: { timeScale: scale } });
|
const res = await page.request.post('/api/sim', { data: { timeScale: scale, paused: false } });
|
||||||
expect(res.status()).toBe(200);
|
expect(res.status()).toBe(200);
|
||||||
const body = (await res.json()) as { timeScale: number };
|
const body = (await res.json()) as { timeScale: number };
|
||||||
expect(body.timeScale, `timeScale should be ${scale} after POST /api/sim`).toBe(scale);
|
expect(body.timeScale, `timeScale should be ${scale} after POST /api/sim`).toBe(scale);
|
||||||
@@ -266,20 +267,35 @@ test('plane markers move while flying and the plane popup shows status + route',
|
|||||||
}, { timeout: 15_000, message: 'waiting for the paused clock to freeze the plane position' })
|
}, { timeout: 15_000, message: 'waiting for the paused clock to freeze the plane position' })
|
||||||
.toBe(true);
|
.toBe(true);
|
||||||
|
|
||||||
// Fetch + project in one evaluate — with the sim paused above, the server's analytic
|
// Click the RENDERED marker position, not a fresh /api/state fetch. With the sim paused
|
||||||
// position is static, so the projected point matches what the map renders.
|
// above the server's analytic position is static — but the map renders from its own ~1 s
|
||||||
|
// poll, so right after the freeze confirmation the last rendered frame can still be up to
|
||||||
|
// one poll interval stale (tens of px at scale 1000 on this leg) and a click projected
|
||||||
|
// from a fresh fetch misses the small circle layer (CI run #37). Poll for the plane's
|
||||||
|
// rendered feature instead and project ITS coordinates — exactly what the map draws.
|
||||||
|
// Find + project in one evaluate so nothing can change between the two steps.
|
||||||
const pt = await page.evaluate(async () => {
|
const pt = await page.evaluate(async () => {
|
||||||
const m = (window as any).__flightMap;
|
const m = (window as any).__flightMap;
|
||||||
if (!m) return null;
|
if (!m) return null;
|
||||||
const res = await fetch('/api/state', { cache: 'no-store' });
|
const deadline = Date.now() + 5_000;
|
||||||
const body = (await res.json()) as StateBody;
|
for (;;) {
|
||||||
const p = body.planes.find((x) => x.id === 'plane-starter');
|
let feats: Array<{ properties?: Record<string, unknown>; geometry?: { coordinates: number[] } }> = [];
|
||||||
if (!p || p.status !== 'flying') return null;
|
try {
|
||||||
const projected = m.project([p.lon, p.lat]);
|
feats = m.queryRenderedFeatures(undefined, { layers: ['planes-flying', 'planes-grounded'] });
|
||||||
|
} catch {
|
||||||
|
// map not ready yet — keep polling
|
||||||
|
}
|
||||||
|
const f = feats.find((x) => x.properties?.id === 'plane-starter');
|
||||||
|
if (f && f.geometry) {
|
||||||
|
const projected = m.project(f.geometry.coordinates);
|
||||||
const rect = m.getContainer().getBoundingClientRect();
|
const rect = m.getContainer().getBoundingClientRect();
|
||||||
return { x: rect.left + projected.x, y: rect.top + projected.y };
|
return { x: rect.left + projected.x, y: rect.top + projected.y };
|
||||||
|
}
|
||||||
|
if (Date.now() >= deadline) return null;
|
||||||
|
await new Promise((r) => setTimeout(r, 100));
|
||||||
|
}
|
||||||
});
|
});
|
||||||
expect(pt).not.toBeNull(); // the ~10 s window at scale 1000 is still open this early after departure
|
expect(pt, 'plane marker not rendered after pause').not.toBeNull();
|
||||||
|
|
||||||
await page.mouse.click(pt!.x, pt!.y);
|
await page.mouse.click(pt!.x, pt!.y);
|
||||||
const popup = page.getByTestId('plane-popup');
|
const popup = page.getByTestId('plane-popup');
|
||||||
|
|||||||
+50
-30
@@ -4,6 +4,8 @@ import { test, expect, type Page } from '@playwright/test';
|
|||||||
// The panes render from the shell's single /api/state poll (lib/useGameState.ts); time
|
// The panes render from the shell's single /api/state poll (lib/useGameState.ts); time
|
||||||
// controls POST to /api/sim and refetch immediately, so UI assertions settle within a tick.
|
// controls POST to /api/sim and refetch immediately, so UI assertions settle within a tick.
|
||||||
|
|
||||||
|
const SCALE = 1000; // fastest sim speed — top of the v0.14.0 ladder (same convention as e2e/sim.spec.ts)
|
||||||
|
|
||||||
interface SimState {
|
interface SimState {
|
||||||
clockMs: number;
|
clockMs: number;
|
||||||
timeScale: number;
|
timeScale: number;
|
||||||
@@ -60,48 +62,61 @@ test('left pane renders wallet, reputation and the starter fleet at Frankfurt',
|
|||||||
await expect(row).toContainText(truth.locationName);
|
await expect(row).toContainText(truth.locationName);
|
||||||
}
|
}
|
||||||
|
|
||||||
// v0.12.0 loadout: "n/capacity pkgs" (capacity from the snapshot catalog — ATR 72-600 = 6).
|
// v0.27.0 loadout: "X.Xt / Y.Yt" tonnage (used/max payload from the snapshot catalog — ATR 72-600 = 4.8t).
|
||||||
const loadout = page.getByTestId('plane-loadout-plane-starter');
|
const loadout = page.getByTestId('plane-loadout-plane-starter');
|
||||||
await expect(loadout).toBeVisible();
|
await expect(loadout).toBeVisible();
|
||||||
expect((await loadout.textContent()) ?? '').toMatch(/^\d+\/6 pkgs$/);
|
expect((await loadout.textContent()) ?? '').toMatch(/^\d+\.\dt \/ \d+\.\dt$/);
|
||||||
|
|
||||||
// Sim clock renders (UTC wall-clock of the game time).
|
// Sim clock renders (UTC wall-clock of the game time).
|
||||||
await expect(page.getByTestId('sim-clock')).toContainText(/UTC/);
|
await expect(page.getByTestId('sim-clock')).toContainText(/UTC/);
|
||||||
|
|
||||||
|
// ISS-021 (v0.20.0): the On board section moved to the left pane (between Fleet and Time) —
|
||||||
|
// its heading renders here…
|
||||||
|
await expect(page.getByTestId('left-pane').getByRole('heading', { name: 'On board', exact: true })).toBeVisible();
|
||||||
|
// …and no longer in the right pane.
|
||||||
|
await expect(page.getByTestId('right-pane').getByRole('heading', { name: 'On board', exact: true })).toHaveCount(0);
|
||||||
|
|
||||||
|
// ISS-035 (v0.23.0): the Refuel-to-full row moved to the left pane next to Relocate — its section
|
||||||
|
// heading and button render here…
|
||||||
|
await expect(page.getByTestId('left-pane').getByRole('heading', { name: 'Refuel', exact: true })).toBeVisible();
|
||||||
|
await expect(page.getByTestId('left-pane').getByTestId('market-refuel')).toBeVisible();
|
||||||
|
// …and neither the heading nor the row remains in the right pane.
|
||||||
|
await expect(page.getByTestId('right-pane').getByRole('heading', { name: 'Refuel', exact: true })).toHaveCount(0);
|
||||||
|
await expect(page.getByTestId('right-pane').getByTestId('market-refuel')).toHaveCount(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('time controls: pause freezes the sim and the ladder slider sets timeScale', async ({ page }) => {
|
test('sim clock ticks smoothly between polls — seconds advance without waiting for a snapshot (ISS-007)', async ({ page }) => {
|
||||||
await page.goto('/');
|
await page.goto('/');
|
||||||
const pauseBtn = page.getByTestId('pause-toggle');
|
const clock = page.getByTestId('sim-clock');
|
||||||
await expect(pauseBtn).toBeVisible({ timeout: 15_000 });
|
await expect(clock).toBeVisible({ timeout: 15_000 });
|
||||||
|
|
||||||
// Pause via the UI button — assert against the authoritative /api/state…
|
// Fastest scale so game seconds move visibly inside the sampling window.
|
||||||
await pauseBtn.click();
|
const post = await page.request.post('/api/sim', { data: { timeScale: SCALE, paused: false } });
|
||||||
await expect.poll(async () => (await getState(page)).simState.paused, { timeout: 10_000 }).toBe(true);
|
expect(post.status()).toBe(200);
|
||||||
// …and in the pane itself (the refetch after POST flips the button to Resume).
|
|
||||||
await expect(pauseBtn).toHaveText('Resume');
|
|
||||||
|
|
||||||
// Scale via the ladder slider. End jumps to max (t=1 → 1000×): the label updates
|
// "YYYY-MM-DD HH:MM:SS UTC" → epoch ms (UTC). While running there is no "(paused)" suffix.
|
||||||
// optimistically on input, and release flushes the debounced POST immediately.
|
const sample = async () => {
|
||||||
const slider = page.getByTestId('time-scale-slider');
|
const text = ((await clock.textContent()) ?? '').trim();
|
||||||
await slider.focus();
|
expect(text, `clock format: ${text}`).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} UTC$/);
|
||||||
await page.keyboard.press('End');
|
return Date.parse(text.replace(' ', 'T').replace(' UTC', 'Z'));
|
||||||
await expect(page.getByTestId('time-scale-value')).toHaveText('1000×', { timeout: 10_000 });
|
};
|
||||||
await expect.poll(async () => (await getState(page)).simState.timeScale, { timeout: 10_000 }).toBe(1000);
|
|
||||||
|
|
||||||
// Home jumps to min (t=0 → 1×).
|
// Three samples ~1.3 s apart real time: at scale 1000 each gap is ≈1300 game seconds, so the
|
||||||
await page.keyboard.press('Home');
|
// displayed clock must strictly advance between CONSECUTIVE samples — with the old poll-only
|
||||||
await expect(page.getByTestId('time-scale-value')).toHaveText('1×', { timeout: 10_000 });
|
// rendering a sample pair could straddle zero snapshot updates and show no change at all.
|
||||||
await expect.poll(async () => (await getState(page)).simState.timeScale, { timeout: 10_000 }).toBe(1);
|
const t0 = await sample();
|
||||||
|
await new Promise((r) => setTimeout(r, 1_300));
|
||||||
|
const t1 = await sample();
|
||||||
|
await new Promise((r) => setTimeout(r, 1_300));
|
||||||
|
const t2 = await sample();
|
||||||
|
|
||||||
// Game clock shows seconds: YYYY-MM-DD HH:MM:SS UTC.
|
expect(t1).toBeGreaterThan(t0);
|
||||||
await expect(page.getByTestId('sim-clock')).toContainText(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} UTC/);
|
expect(t2).toBeGreaterThan(t1);
|
||||||
|
// Sanity: ~2.6 s real × 1000 ≈ 2.6 M game ms — generous bounds keep slow CI boxes safe while
|
||||||
// Restore the live instance to scale 1 + unpaused (afterEach enforces this too).
|
// still catching a frozen or wildly mis-scaled clock.
|
||||||
const restore = await page.request.post('/api/sim', { data: { timeScale: 1, paused: false } });
|
const total = t2 - t0;
|
||||||
expect(restore.status()).toBe(200);
|
expect(total).toBeGreaterThanOrEqual(1_000_000);
|
||||||
const after = await getState(page);
|
expect(total).toBeLessThanOrEqual(6_000_000);
|
||||||
expect(after.simState.timeScale).toBe(1);
|
|
||||||
expect(after.simState.paused).toBe(false);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test('slider commit keeps the chosen scale on screen until confirmed — no snap-back (ISS-001)', async ({ page }) => {
|
test('slider commit keeps the chosen scale on screen until confirmed — no snap-back (ISS-001)', async ({ page }) => {
|
||||||
@@ -140,4 +155,9 @@ test('right pane placeholder exists with the Jobs & Market heading', async ({ pa
|
|||||||
const right = page.getByTestId('right-pane');
|
const right = page.getByTestId('right-pane');
|
||||||
await expect(right).toBeVisible();
|
await expect(right).toBeVisible();
|
||||||
await expect(right).toContainText('Jobs & Market');
|
await expect(right).toContainText('Jobs & Market');
|
||||||
|
|
||||||
|
// v0.28.0 (ISS-047): the Jobs / Planes market tab bar renders once a snapshot lands; Jobs is default-active.
|
||||||
|
await expect(page.getByTestId('tab-jobs'), 'the Jobs tab button appears').toBeVisible({ timeout: 15_000 });
|
||||||
|
await expect(page.getByTestId('tab-planes-market')).toBeVisible();
|
||||||
|
await expect(page.getByTestId('tab-jobs')).toHaveAttribute('aria-selected', 'true');
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,384 @@
|
|||||||
|
import { test, expect, type Page } from '@playwright/test';
|
||||||
|
|
||||||
|
// v0.26.0 — ISS-043 part 2 (UI): the flight queue. A plane's not-yet-started legs show up in a
|
||||||
|
// Queue sub-section of its on-board block (add via airport select + button, cancel per leg), and
|
||||||
|
// a flying plane with queued legs draws them as a DOTTED line (`queue-routes` layer) chaining
|
||||||
|
// dest → queue[0] → … — the active leg stays in the solid `routes-legs` layer. Landing auto-starts
|
||||||
|
// the next queued leg server-side (part 1); test 3 exercises that chain end-to-end through the API.
|
||||||
|
|
||||||
|
const SCALE = 1000; // fastest sim speed (v0.14.0 ladder top) — keeps flights to seconds of real time
|
||||||
|
const HUB = 'EDDF'; // must match HUB_ICAO in lib/game/seed.ts
|
||||||
|
const DEST = 'LEMD'; // Madrid–Barajas — the typical long leg (~10 s at scale 1000)
|
||||||
|
const QUEUE = 'EHAM'; // Amsterdam — a third airport, distinct from hub and destination
|
||||||
|
|
||||||
|
interface PlaneState {
|
||||||
|
id: string;
|
||||||
|
status: 'available' | 'flying';
|
||||||
|
locationIcao: string;
|
||||||
|
destIcao: string | null;
|
||||||
|
queue: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PackageState {
|
||||||
|
id: string;
|
||||||
|
originIcao: string;
|
||||||
|
destIcao: string;
|
||||||
|
status: 'open' | 'loaded' | 'delivered' | 'expired' | 'abandoned';
|
||||||
|
planeId: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface StateBody {
|
||||||
|
account: { cash: number; reputation: number };
|
||||||
|
simState: { clockMs: number; timeScale: number; paused: boolean };
|
||||||
|
planes: PlaneState[];
|
||||||
|
packages: PackageState[];
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getState(page: Page): Promise<StateBody> {
|
||||||
|
const res = await page.request.get('/api/state');
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
return (await res.json()) as StateBody;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function postSim(page: Page, body: unknown) {
|
||||||
|
return page.request.post('/api/sim', { data: body });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set the time scale and VERIFY from the response that it stuck. ISS-041 also clears pause: a
|
||||||
|
// landing pauses the sim, so any fast-forward after one must resume it or the clock stays frozen.
|
||||||
|
async function setScale(page: Page, scale: number): Promise<void> {
|
||||||
|
const res = await page.request.post('/api/sim', { data: { timeScale: scale, paused: false } });
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
const body = (await res.json()) as { timeScale: number };
|
||||||
|
expect(body.timeScale, `timeScale should be ${scale} after POST /api/sim`).toBe(scale);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Leave the live instance in a sane state for the other specs (scale 1, running).
|
||||||
|
test.afterEach(async ({ page }) => {
|
||||||
|
const res = await postSim(page, { timeScale: 1, paused: false });
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test hook (FLIGHT_TEST_HOOKS=1): create an open package on a known route.
|
||||||
|
async function createPackage(page: Page, fromIcao: string, toIcao: string): Promise<PackageState> {
|
||||||
|
const created = await page.request.post('/api/test/create-package', {
|
||||||
|
data: { originIcao: fromIcao, destIcao: toIcao, deadlineOffsetMs: 24 * 3_600_000 },
|
||||||
|
});
|
||||||
|
expect(created.status()).toBe(201);
|
||||||
|
return (await created.json()) as PackageState;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Self-heal: let any in-flight leg finish, reposition plane-starter home via the API, and abandon
|
||||||
|
// leftover cargo so every test starts from the canonical state even after an interrupted run.
|
||||||
|
async function flyHomeViaApi(page: Page): Promise<void> {
|
||||||
|
let s = await getState(page);
|
||||||
|
let plane = s.planes.find((p) => p.id === 'plane-starter')!;
|
||||||
|
if (plane.status === 'flying' || plane.locationIcao !== HUB) {
|
||||||
|
// Fast-forward any leftover leg / repositioning flight (~20 s real time worst case at 1000×).
|
||||||
|
await setScale(page, SCALE);
|
||||||
|
}
|
||||||
|
if (plane.status === 'flying') {
|
||||||
|
// While flying, locationIcao stays at the DEPARTURE airport — re-read state after landing.
|
||||||
|
await expect
|
||||||
|
.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')?.status ?? ''), {
|
||||||
|
timeout: 240_000,
|
||||||
|
message: 'waiting for an in-flight plane-starter to land',
|
||||||
|
})
|
||||||
|
.toBe('available');
|
||||||
|
s = await getState(page);
|
||||||
|
plane = s.planes.find((p) => p.id === 'plane-starter')!;
|
||||||
|
}
|
||||||
|
if (plane.locationIcao !== HUB) {
|
||||||
|
// ISS-041: the landing above paused the sim — setScale clears pause so the return leg fast-forwards.
|
||||||
|
await setScale(page, SCALE);
|
||||||
|
const res = await page.request.post(`/api/planes/${plane.id}/fly`, { data: { destIcao: HUB } });
|
||||||
|
expect(res.status()).toBe(200); // repositioning needs no package (v0.12.0 manual flight)
|
||||||
|
await expect
|
||||||
|
.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')?.locationIcao ?? ''), {
|
||||||
|
timeout: 240_000,
|
||||||
|
message: 'waiting for plane-starter to land back at the hub',
|
||||||
|
})
|
||||||
|
.toBe(HUB);
|
||||||
|
}
|
||||||
|
// Abandon leftover loaded/expired packages (the baseline is captured AFTER this cleanup).
|
||||||
|
const s1 = await getState(page);
|
||||||
|
for (const pkg of s1.packages) {
|
||||||
|
if (pkg.planeId === 'plane-starter' && (pkg.status === 'loaded' || pkg.status === 'expired')) {
|
||||||
|
const res = await page.request.post(`/api/packages/${pkg.id}/abandon`);
|
||||||
|
expect(res.ok()).toBeTruthy();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function waitForAirportCount(page: Page): Promise<void> {
|
||||||
|
const countEl = page.getByTestId('airport-count');
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const text = (await countEl.textContent()) ?? '';
|
||||||
|
const m = text.match(/(\d+)/);
|
||||||
|
return m ? parseInt(m[1], 10) : -1;
|
||||||
|
}).toBeGreaterThan(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rendered features of the given layers in the current viewport, [] until the map exists.
|
||||||
|
function renderedFeatures(
|
||||||
|
page: Page,
|
||||||
|
layers: string[],
|
||||||
|
): Promise<Array<{ type?: unknown; id?: unknown; properties?: unknown; geometry?: unknown }>> {
|
||||||
|
return page.evaluate((ls: string[]) => {
|
||||||
|
const m = (window as any).__flightMap;
|
||||||
|
if (!m) return [];
|
||||||
|
try {
|
||||||
|
// queryRenderedFeatures returns live GeoJSONFeature instances whose `geometry` is a lazy
|
||||||
|
// PROTOTYPE getter — Playwright's evaluate serialization copies only own enumerable props, so
|
||||||
|
// geometry silently vanishes across the page boundary. Map to plain objects IN-PAGE (ORCHESTRATOR §6).
|
||||||
|
return (m.queryRenderedFeatures(undefined, { layers: ls }) as Array<{
|
||||||
|
type?: unknown;
|
||||||
|
id?: unknown;
|
||||||
|
properties?: unknown;
|
||||||
|
geometry?: unknown;
|
||||||
|
}>).map((f) => ({
|
||||||
|
type: f.type,
|
||||||
|
id: f.id,
|
||||||
|
properties: f.properties,
|
||||||
|
geometry: f.geometry,
|
||||||
|
}));
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}, layers);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fit the map so all given airports are in-viewport — queryRenderedFeatures only returns features
|
||||||
|
// rendered inside the CURRENT viewport (same helper as e2e/hover.spec.ts).
|
||||||
|
async function fitToAirports(page: Page, icaos: string[]): Promise<void> {
|
||||||
|
const fc = (await (await page.request.get('/api/airports')).json()) as {
|
||||||
|
features: Array<{ properties: { icao: string; lat: number; lon: number } }>;
|
||||||
|
};
|
||||||
|
const points = icaos.map((icao) => {
|
||||||
|
const f = fc.features.find((x) => x.properties.icao === icao);
|
||||||
|
if (!f) throw new Error(`airport ${icao} not found in /api/airports`);
|
||||||
|
return [f.properties.lon, f.properties.lat] as [number, number];
|
||||||
|
});
|
||||||
|
await page.evaluate((pts: [number, number][]) => {
|
||||||
|
const m = (window as any).__flightMap;
|
||||||
|
if (!m) throw new Error('map not ready');
|
||||||
|
const lons = pts.map((p) => p[0]);
|
||||||
|
const lats = pts.map((p) => p[1]);
|
||||||
|
// duration 0 → instant camera jump, no animation to wait out.
|
||||||
|
m.fitBounds(
|
||||||
|
[
|
||||||
|
[Math.min(...lons), Math.min(...lats)],
|
||||||
|
[Math.max(...lons), Math.max(...lats)],
|
||||||
|
],
|
||||||
|
{ padding: 40, duration: 0 },
|
||||||
|
);
|
||||||
|
}, points);
|
||||||
|
// Give the renderer a beat after the camera jump before asserting on rendered features.
|
||||||
|
await page.waitForTimeout(300);
|
||||||
|
}
|
||||||
|
|
||||||
|
// [lon, lat] of an airport from the same /api/airports dataset the map draws its lines from.
|
||||||
|
async function airportLonLat(page: Page, icao: string): Promise<[number, number]> {
|
||||||
|
const fc = (await (await page.request.get('/api/airports')).json()) as {
|
||||||
|
features: Array<{ properties: { icao: string; lat: number; lon: number } }>;
|
||||||
|
};
|
||||||
|
const f = fc.features.find((x) => x.properties.icao === icao);
|
||||||
|
if (!f) throw new Error(`airport ${icao} not found in /api/airports`);
|
||||||
|
return [f.properties.lon, f.properties.lat];
|
||||||
|
}
|
||||||
|
|
||||||
|
// MapLibre stores GeoJSON geometry in per-tile INTEGER grids and clips long lines across tiles, so
|
||||||
|
// queryRenderedFeatures returns ONE FEATURE PER TILE the line crosses with coordinates quantized to
|
||||||
|
// the grid — check endpoints ACROSS all segments with an EPS (same pattern as expectHoverRoute in
|
||||||
|
// e2e/hover.spec.ts). ~5 km: above worst-case quantization at any zoom, below the distance between
|
||||||
|
// any two EU airports.
|
||||||
|
const QUEUE_ROUTE_EPS_DEG = 0.05;
|
||||||
|
|
||||||
|
test.describe.configure({ mode: 'serial' }); // shared live DB — order matters within this file
|
||||||
|
|
||||||
|
test('queue display + cancel via UI (ISS-043 part 2)', async ({ page }) => {
|
||||||
|
test.setTimeout(300_000); // self-heal can take minutes after an interrupted run
|
||||||
|
await flyHomeViaApi(page); // deterministic: the starter sits grounded at EDDF
|
||||||
|
|
||||||
|
// Full tank before departure — keeps the long EDDF→LEMD leg fuel-feasible (same as tests 2 & 3).
|
||||||
|
const refuel = await page.request.post('/api/planes/plane-starter/refuel');
|
||||||
|
expect(refuel.status()).toBe(200);
|
||||||
|
|
||||||
|
const pkg = await createPackage(page, HUB, DEST);
|
||||||
|
|
||||||
|
await page.goto('/');
|
||||||
|
await waitForAirportCount(page);
|
||||||
|
|
||||||
|
// LOAD via the UI (right-pane job list) — the starter is grounded at the package's origin.
|
||||||
|
const loadBtn = page.getByTestId(`load-${pkg.id}`);
|
||||||
|
await expect(loadBtn, 'Load button enabled for a package at the hub').toBeEnabled({ timeout: 15_000 });
|
||||||
|
await loadBtn.click();
|
||||||
|
const onboardRow = page.getByTestId(`onboard-package-${pkg.id}`);
|
||||||
|
await expect(onboardRow, 'loaded package appears in the On board section').toBeVisible({ timeout: 15_000 });
|
||||||
|
|
||||||
|
// LeftPane's own /api/airports fetch populates the queue-add select — wait for it.
|
||||||
|
const addSelect = page.getByTestId('queue-add-dest');
|
||||||
|
await expect(addSelect.locator(`option[value="${QUEUE}"]`)).toHaveCount(1, { timeout: 15_000 });
|
||||||
|
|
||||||
|
// START leg 1 via the UI (fly-to button in the on-board block).
|
||||||
|
const flyBtn = page.getByTestId(`fly-to-${pkg.id}`);
|
||||||
|
await expect(flyBtn).toBeEnabled();
|
||||||
|
await flyBtn.click();
|
||||||
|
// The click fires the fly POST asynchronously — poll until it took effect server-side, then FREEZE
|
||||||
|
// immediately: at scale 1000 (left over from self-heal) the ~10 s leg would otherwise land under us.
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const p = (await getState(page)).planes.find((x) => x.id === 'plane-starter');
|
||||||
|
return !!p && p.status === 'flying' && p.destIcao === DEST;
|
||||||
|
}, { timeout: 15_000, message: 'waiting for the fly click to take effect (status "flying" + dest set)' }).toBe(true);
|
||||||
|
await postSim(page, { paused: true }); // pause-sim pattern: deterministic window for UI clicks
|
||||||
|
|
||||||
|
// ADD a leg to the queue via the UI. The button is disabled until an airport is selected…
|
||||||
|
const addButton = page.getByTestId('queue-add');
|
||||||
|
await expect(addButton).toBeDisabled();
|
||||||
|
await addSelect.selectOption(QUEUE);
|
||||||
|
await expect(addButton).toBeEnabled();
|
||||||
|
await addButton.click();
|
||||||
|
|
||||||
|
// …and the new leg appears as queue-leg-0 with its destination.
|
||||||
|
const legRow = page.getByTestId('queue-leg-0');
|
||||||
|
await expect(legRow, 'the queued leg appears in the Queue sub-section').toContainText(QUEUE, { timeout: 15_000 });
|
||||||
|
|
||||||
|
// CANCEL it via the UI and assert it's gone.
|
||||||
|
await page.getByTestId('queue-cancel-0').click();
|
||||||
|
await expect(page.getByTestId('queue-leg-0'), 'the cancelled leg is removed from the queue').toHaveCount(0, { timeout: 15_000 });
|
||||||
|
|
||||||
|
// Cleanup: resume + fast-forward to arrival at DEST (empty queue → plain landing), then fly home.
|
||||||
|
await setScale(page, SCALE);
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const p = (await getState(page)).planes.find((x) => x.id === 'plane-starter');
|
||||||
|
return !!p && p.status === 'available' && p.locationIcao === DEST;
|
||||||
|
}, { timeout: 120_000, message: `waiting for plane-starter to land at ${DEST}` }).toBe(true);
|
||||||
|
|
||||||
|
// ISS-041: the arrival above paused the sim — setScale clears pause for the return leg.
|
||||||
|
await setScale(page, SCALE);
|
||||||
|
const home = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||||
|
expect(home.status()).toBe(200);
|
||||||
|
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')?.locationIcao ?? ''), {
|
||||||
|
timeout: 120_000,
|
||||||
|
message: 'waiting for plane-starter to land back at the hub',
|
||||||
|
}).toBe(HUB);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('dotted queue line renders the queued path on the map (ISS-043 part 2)', async ({ page }) => {
|
||||||
|
test.setTimeout(300_000); // self-heal + one flight at scale 1000 + fly-home cleanup
|
||||||
|
await flyHomeViaApi(page);
|
||||||
|
|
||||||
|
// Full tank before departure — keeps the state canonical for whatever the cleanup does.
|
||||||
|
const refuel = await page.request.post('/api/planes/plane-starter/refuel');
|
||||||
|
expect(refuel.status()).toBe(200);
|
||||||
|
|
||||||
|
// Load + queue + fly via the API: a package EDDF→LEMD, one queued leg LEMD→EHAM (works while
|
||||||
|
// grounded — part 1), then start leg 1. The dotted line must show ONLY dest → queue[0].
|
||||||
|
const pkg = await createPackage(page, HUB, DEST);
|
||||||
|
const load = await page.request.post(`/api/packages/${pkg.id}/load`, { data: { planeId: 'plane-starter' } });
|
||||||
|
expect(load.status()).toBe(200);
|
||||||
|
const queueRes = await page.request.post('/api/planes/plane-starter/queue', { data: { destIcao: QUEUE } });
|
||||||
|
expect(queueRes.status()).toBe(200);
|
||||||
|
const flyRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: DEST } });
|
||||||
|
expect(flyRes.status()).toBe(200);
|
||||||
|
// The endpoint's OWN post-action snapshot already shows the plane flying — no poll race.
|
||||||
|
const flyBody = (await flyRes.json()) as StateBody;
|
||||||
|
expect(flyBody.planes.find((p) => p.id === 'plane-starter')?.status).toBe('flying');
|
||||||
|
|
||||||
|
// Freeze mid-flight so the ~10 s leg can't land under us while we assert.
|
||||||
|
await postSim(page, { paused: true });
|
||||||
|
|
||||||
|
await page.goto('/');
|
||||||
|
await waitForAirportCount(page);
|
||||||
|
// All line endpoints must be in-viewport for queryRenderedFeatures to see them.
|
||||||
|
await fitToAirports(page, [DEST, QUEUE]);
|
||||||
|
|
||||||
|
const destLL = await airportLonLat(page, DEST);
|
||||||
|
const queueLL = await airportLonLat(page, QUEUE);
|
||||||
|
const hubLL = await airportLonLat(page, HUB);
|
||||||
|
const near = (a: [number, number], b: [number, number]) =>
|
||||||
|
Math.abs(a[0] - b[0]) <= QUEUE_ROUTE_EPS_DEG && Math.abs(a[1] - b[1]) <= QUEUE_ROUTE_EPS_DEG;
|
||||||
|
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const feats = (await renderedFeatures(page, ['queue-routes'])) as Array<{
|
||||||
|
properties?: Record<string, unknown>;
|
||||||
|
geometry?: { type: string; coordinates: [number, number][] };
|
||||||
|
}>;
|
||||||
|
// Filter to real LineString segments — keeps this poll callback total (a throw inside
|
||||||
|
// expect.poll fails the test instantly instead of retrying). "None yet" → keep polling.
|
||||||
|
const segs = feats.filter(
|
||||||
|
(f): f is { properties?: Record<string, unknown>; geometry: { type: 'LineString'; coordinates: [number, number][] } } =>
|
||||||
|
!!f.geometry && f.geometry.type === 'LineString' && Array.isArray(f.geometry.coordinates) && f.geometry.coordinates.length >= 2,
|
||||||
|
);
|
||||||
|
if (!segs.length) return false;
|
||||||
|
// The line may be clipped into several per-tile segments — check the endpoints across all of them:
|
||||||
|
// some segment STARTS within EPS of DEST (the active leg's destination, NOT the plane's origin)…
|
||||||
|
const startsAtDest = segs.some((f) => near(f.geometry.coordinates[0], destLL));
|
||||||
|
// …and some ENDS within EPS of the queued airport.
|
||||||
|
const endsAtQueue = segs.some((f) => {
|
||||||
|
const c = f.geometry.coordinates;
|
||||||
|
return near(c[c.length - 1], queueLL);
|
||||||
|
});
|
||||||
|
// The active leg (HUB→DEST) must NOT be in this layer — no segment may start at the hub.
|
||||||
|
const noneStartsAtHub = !segs.some((f) => near(f.geometry.coordinates[0], hubLL));
|
||||||
|
// Every rendered feature belongs to plane-starter (the only queued plane).
|
||||||
|
const ownedByStarter = feats.every((f) => f.properties?.planeId === 'plane-starter');
|
||||||
|
return startsAtDest && endsAtQueue && noneStartsAtHub && ownedByStarter;
|
||||||
|
}, { timeout: 15_000, message: `waiting for the dotted queue line ${DEST} → ${QUEUE}` }).toBe(true);
|
||||||
|
|
||||||
|
// Cleanup: cancel the queued leg (so landing at DEST is a plain grounding), resume + fast-forward
|
||||||
|
// to arrival, then fly home.
|
||||||
|
const cancelRes = await page.request.post('/api/planes/plane-starter/queue/cancel', { data: { index: 0 } });
|
||||||
|
expect(cancelRes.status()).toBe(200);
|
||||||
|
await setScale(page, SCALE);
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const p = (await getState(page)).planes.find((x) => x.id === 'plane-starter');
|
||||||
|
return !!p && p.status === 'available' && p.locationIcao === DEST;
|
||||||
|
}, { timeout: 120_000, message: `waiting for plane-starter to land at ${DEST}` }).toBe(true);
|
||||||
|
|
||||||
|
// ISS-041: the arrival above paused the sim — setScale clears pause for the return leg.
|
||||||
|
await setScale(page, SCALE);
|
||||||
|
const home = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||||
|
expect(home.status()).toBe(200);
|
||||||
|
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')?.locationIcao ?? ''), {
|
||||||
|
timeout: 120_000,
|
||||||
|
message: 'waiting for plane-starter to land back at the hub',
|
||||||
|
}).toBe(HUB);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('landing auto-starts the next queued leg (ISS-043 chain end-to-end)', async ({ page }) => {
|
||||||
|
test.setTimeout(300_000); // self-heal + two chained legs at scale 1000
|
||||||
|
await flyHomeViaApi(page);
|
||||||
|
|
||||||
|
// Full tank so fuel covers the chained return leg (same feasibility rule as /fly).
|
||||||
|
const refuel = await page.request.post('/api/planes/plane-starter/refuel');
|
||||||
|
expect(refuel.status()).toBe(200);
|
||||||
|
|
||||||
|
// Package EDDF→LEMD + a queued return leg LEMD→EDDF, then start leg 1.
|
||||||
|
const pkg = await createPackage(page, HUB, DEST);
|
||||||
|
const load = await page.request.post(`/api/packages/${pkg.id}/load`, { data: { planeId: 'plane-starter' } });
|
||||||
|
expect(load.status()).toBe(200);
|
||||||
|
const queueRes = await page.request.post('/api/planes/plane-starter/queue', { data: { destIcao: HUB } });
|
||||||
|
expect(queueRes.status()).toBe(200);
|
||||||
|
const flyRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: DEST } });
|
||||||
|
expect(flyRes.status()).toBe(200);
|
||||||
|
|
||||||
|
// Fast-forward (also clears any pause). On landing at DEST the server must AUTO-START the queued
|
||||||
|
// return leg — no manual dispatch. The chained state persists for the whole ~10 s return leg, so a
|
||||||
|
// poll can't miss it: status 'flying' with destIcao = the first (only) queued ICAO.
|
||||||
|
await setScale(page, SCALE);
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const p = (await getState(page)).planes.find((x) => x.id === 'plane-starter');
|
||||||
|
return !!p && p.status === 'flying' && p.destIcao === HUB;
|
||||||
|
}, { timeout: 120_000, message: `waiting for the auto-chained leg ${DEST} → ${HUB} to start` }).toBe(true);
|
||||||
|
|
||||||
|
// Cargo delivery ran BEFORE chaining (part 1 ordering) — the package is already delivered.
|
||||||
|
const s = await getState(page);
|
||||||
|
expect(s.packages.find((x) => x.id === pkg.id)?.status).toBe('delivered');
|
||||||
|
|
||||||
|
// Let the chained leg finish: it lands back at the hub, leaving the canonical onboarding state.
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const p = (await getState(page)).planes.find((x) => x.id === 'plane-starter');
|
||||||
|
return !!p && p.status === 'available' && p.locationIcao === HUB;
|
||||||
|
}, { timeout: 120_000, message: `waiting for the chained leg to land back at ${HUB}` }).toBe(true);
|
||||||
|
});
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
import type { Page } from '@playwright/test';
|
||||||
|
import { expect, test } from '@playwright/test';
|
||||||
|
|
||||||
|
// v0.18.0 — ISS-010: relocating a GROUNDED (empty) plane to any airport against the live origin.
|
||||||
|
// Two UI surfaces drive the EXISTING POST /api/planes/{id}/fly endpoint (pure repositioning has
|
||||||
|
// been allowed since v0.12.0 — no API change): the left-pane Relocate section (ISS-023, v0.21.0)
|
||||||
|
// (relocate-plane / relocate-dest / relocate-go) and the Relocate row inside the airport popup on
|
||||||
|
// the map (airport-popup-plane / airport-popup-relocate). Marker-size regression is covered by
|
||||||
|
// the existing e2e/map.spec.ts click tests, not here.
|
||||||
|
|
||||||
|
const SCALE = 1000; // fastest sim speed (v0.14.0 ladder top) — keeps cleanup flights to seconds of real time
|
||||||
|
const HUB = 'EDDF'; // Frankfurt Main — the seeded starter plane's home base (lib/game/seed.ts)
|
||||||
|
// LFRS Nantes Atlantique — same isolated marker as e2e/map.spec.ts: its nearest neighbour is ~78 px
|
||||||
|
// away at the initial zoom, so a click on its projected center cannot hit another circle.
|
||||||
|
const POPUP_AIRPORT = { icao: 'LFRS', lon: -1.61073, lat: 47.153198 };
|
||||||
|
|
||||||
|
interface StateBody {
|
||||||
|
planes: Array<{ id: string; status: string; locationIcao: string; destIcao: string | null }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getState(page: Page): Promise<StateBody> {
|
||||||
|
const res = await page.request.get('/api/state');
|
||||||
|
expect(res.ok()).toBeTruthy();
|
||||||
|
return (await res.json()) as StateBody;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function postSim(page: Page, body: Record<string, unknown>): Promise<void> {
|
||||||
|
const res = await page.request.post('/api/sim', { data: body });
|
||||||
|
expect(res.ok()).toBeTruthy();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set the time scale and VERIFY from the response that it stuck — if something external ever
|
||||||
|
// resets the live instance's controls mid-test, fail loudly here instead of timing out later.
|
||||||
|
// ISS-041 also clears pause: a landing pauses the sim, so any fast-forward after one must
|
||||||
|
// resume it or the clock stays frozen and the next wait hangs.
|
||||||
|
async function setScale(page: Page, scale: number): Promise<void> {
|
||||||
|
const res = await page.request.post('/api/sim', { data: { timeScale: scale, paused: false } });
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
const body = (await res.json()) as { timeScale: number };
|
||||||
|
expect(body.timeScale, `timeScale should be ${scale} after POST /api/sim`).toBe(scale);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Closest airport to the hub from /api/airports → shortest possible leg (fuel trivial).
|
||||||
|
async function nearestToHub(page: Page): Promise<{ icao: string }> {
|
||||||
|
const res = await page.request.get('/api/airports');
|
||||||
|
expect(res.ok()).toBeTruthy();
|
||||||
|
const fc = (await res.json()) as { features: Array<{ properties: { icao: string; lat: number; lon: number } }> };
|
||||||
|
const hub = fc.features.find((f) => f.properties.icao === HUB)!.properties;
|
||||||
|
let nearest = fc.features.filter((f) => f.properties.icao !== HUB)[0].properties;
|
||||||
|
for (const f of fc.features) {
|
||||||
|
if (f.properties.icao === HUB) continue;
|
||||||
|
const d = Math.hypot(f.properties.lat - hub.lat, f.properties.lon - hub.lon);
|
||||||
|
const dn = Math.hypot(nearest.lat - hub.lat, nearest.lon - hub.lon);
|
||||||
|
if (d < dn) nearest = f.properties;
|
||||||
|
}
|
||||||
|
return { icao: nearest.icao };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Self-heal helper (same pattern as e2e/actions.spec.ts): let any in-flight leg finish and
|
||||||
|
// reposition plane-starter home via the API — repositioning needs no package (v0.12.0 manual
|
||||||
|
// flight) — so every test starts from the canonical state even after an interrupted previous run.
|
||||||
|
async function flyHomeViaApi(page: Page): Promise<void> {
|
||||||
|
let s = await getState(page);
|
||||||
|
let plane = s.planes.find((p) => p.id === 'plane-starter')!;
|
||||||
|
if (plane.status === 'flying' || plane.locationIcao !== HUB) {
|
||||||
|
// Fast-forward any leftover leg / repositioning flight (~20 s real time worst case at 1000×).
|
||||||
|
await setScale(page, SCALE);
|
||||||
|
}
|
||||||
|
if (plane.status === 'flying') {
|
||||||
|
// While flying, locationIcao stays at the DEPARTURE airport — re-read state after landing
|
||||||
|
// before deciding whether a repositioning flight is needed.
|
||||||
|
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.status), { timeout: 240_000 }).toBe('available');
|
||||||
|
s = await getState(page);
|
||||||
|
plane = s.planes.find((p) => p.id === 'plane-starter')!;
|
||||||
|
}
|
||||||
|
if (plane.locationIcao !== HUB) {
|
||||||
|
// ISS-041: the landing above paused the sim — setScale clears pause so the return leg
|
||||||
|
// fast-forwards instead of taking real-time hours.
|
||||||
|
await setScale(page, SCALE);
|
||||||
|
const res = await page.request.post(`/api/planes/${plane.id}/fly`, { data: { destIcao: HUB } });
|
||||||
|
expect(res.ok()).toBeTruthy(); // repositioning needs no package (v0.12.0 manual flight)
|
||||||
|
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.locationIcao), { timeout: 240_000 }).toBe(HUB);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Self-heal in CLEANUP (afterEach): the tests deliberately leave plane-starter mid-flight, so
|
||||||
|
// fast-forward + reposition home here; then restore scale=1 / unpaused for later specs.
|
||||||
|
test.afterEach(async ({ page }) => {
|
||||||
|
await flyHomeViaApi(page);
|
||||||
|
await postSim(page, { timeScale: 1, paused: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
test.describe.configure({ mode: 'serial' }); // shared live DB — order matters within this file
|
||||||
|
|
||||||
|
test('left pane Relocate section relocates a grounded plane', async ({ page }) => {
|
||||||
|
test.setTimeout(300_000); // self-heal (worst case ~20 s at 1000×) + one short leg
|
||||||
|
await flyHomeViaApi(page);
|
||||||
|
|
||||||
|
// Full tank before departure — a partially drained plane left by an earlier spec could not
|
||||||
|
// afford the cleanup round trip.
|
||||||
|
const refuel = await page.request.post('/api/planes/plane-starter/refuel');
|
||||||
|
expect(refuel.ok()).toBeTruthy();
|
||||||
|
|
||||||
|
const nearest = await nearestToHub(page);
|
||||||
|
|
||||||
|
await page.goto('/');
|
||||||
|
const planeSel = page.getByTestId('relocate-plane');
|
||||||
|
await expect(planeSel).toBeVisible({ timeout: 15_000 }); // pane renders once the first snapshot lands
|
||||||
|
await planeSel.selectOption('plane-starter');
|
||||||
|
|
||||||
|
// Destination options come from the one-time /api/airports fetch (sorted by name) — selectOption
|
||||||
|
// waits until the matching option exists, so this doubles as the load wait.
|
||||||
|
const destSel = page.getByTestId('relocate-dest');
|
||||||
|
await destSel.selectOption(nearest.icao);
|
||||||
|
|
||||||
|
const goBtn = page.getByTestId('relocate-go');
|
||||||
|
await expect(goBtn).toBeEnabled();
|
||||||
|
await goBtn.click();
|
||||||
|
|
||||||
|
// The click fires the fly POST asynchronously (runAction is fire-and-forget from the test's view),
|
||||||
|
// so poll until it took effect on the server.
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const b = await getState(page);
|
||||||
|
const p = b.planes.find((x) => x.id === 'plane-starter')!;
|
||||||
|
return p.status === 'flying' && p.destIcao === nearest.icao;
|
||||||
|
}, { timeout: 15_000, message: 'waiting for the relocate click to take effect (status "flying" + dest set)' }).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('airport popup offers Relocate options for grounded planes', async ({ page }) => {
|
||||||
|
test.setTimeout(300_000); // self-heal (worst case ~20 s at 1000×) + one leg to LFRS
|
||||||
|
await flyHomeViaApi(page);
|
||||||
|
|
||||||
|
const refuel = await page.request.post('/api/planes/plane-starter/refuel');
|
||||||
|
expect(refuel.ok()).toBeTruthy();
|
||||||
|
|
||||||
|
await page.goto('/');
|
||||||
|
|
||||||
|
// Wait until the airport count renders (airports loaded) and the map has a snapshot containing
|
||||||
|
// the plane — the popup's Relocate row is built from that same latest snapshot.
|
||||||
|
const countEl = page.getByTestId('airport-count');
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const text = (await countEl.textContent()) ?? '';
|
||||||
|
const m = text.match(/(\d+)/);
|
||||||
|
return m ? parseInt(m[1], 10) : -1;
|
||||||
|
}, { timeout: 15_000 }).toBeGreaterThan(0);
|
||||||
|
await expect.poll(async () =>
|
||||||
|
page.evaluate(() => {
|
||||||
|
const m = (window as any).__flightMap;
|
||||||
|
if (!m || !m.getSource('planes')) return false;
|
||||||
|
try {
|
||||||
|
return m.querySourceFeatures('planes').some((f: { properties?: Record<string, unknown> }) => f.properties?.id === 'plane-starter');
|
||||||
|
} catch {
|
||||||
|
return false; // source not ready yet — keep polling
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
{ timeout: 15_000 },
|
||||||
|
).toBe(true);
|
||||||
|
|
||||||
|
// Click the LFRS marker (projected center — same pattern as e2e/map.spec.ts). The constant is
|
||||||
|
// passed AS AN ARGUMENT: the evaluate callback runs in the browser, where Node-scope values don't exist.
|
||||||
|
const pt = await page.evaluate(({ lon, lat }) => {
|
||||||
|
const map = (window as any).__flightMap;
|
||||||
|
const p = map.project([lon, lat]);
|
||||||
|
const rect = map.getContainer().getBoundingClientRect();
|
||||||
|
return { x: rect.left + p.x, y: rect.top + p.y };
|
||||||
|
}, POPUP_AIRPORT);
|
||||||
|
await page.mouse.click(pt.x, pt.y);
|
||||||
|
|
||||||
|
const popup = page.getByTestId('airport-popup');
|
||||||
|
await expect(popup).toBeVisible();
|
||||||
|
await expect(popup).toContainText(POPUP_AIRPORT.icao);
|
||||||
|
|
||||||
|
// The Relocate row: a select of grounded planes + the button (disabled until one is picked).
|
||||||
|
const planeSel = page.getByTestId('airport-popup-plane');
|
||||||
|
await expect(planeSel).toBeVisible();
|
||||||
|
// Target THE PLANE OPTION specifically — locator('option') also matches the placeholder and
|
||||||
|
// trips strict mode (CI run #51).
|
||||||
|
await expect(planeSel.locator('option[value="plane-starter"]')).toHaveText(/ATR 72-600 — EDDF/);
|
||||||
|
const goBtn = page.getByTestId('airport-popup-relocate');
|
||||||
|
await expect(goBtn).toBeDisabled(); // placeholder selected
|
||||||
|
|
||||||
|
await planeSel.selectOption('plane-starter');
|
||||||
|
await expect(goBtn).toBeEnabled();
|
||||||
|
await goBtn.click();
|
||||||
|
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const b = await getState(page);
|
||||||
|
const p = b.planes.find((x) => x.id === 'plane-starter')!;
|
||||||
|
return p.status === 'flying' && p.destIcao === POPUP_AIRPORT.icao;
|
||||||
|
}, { timeout: 15_000, message: 'waiting for the popup relocate click to take effect (status "flying" + dest set)' }).toBe(true);
|
||||||
|
});
|
||||||
+189
-10
@@ -2,10 +2,12 @@ import type { Page } from '@playwright/test';
|
|||||||
import { expect, test } from '@playwright/test';
|
import { expect, test } from '@playwright/test';
|
||||||
|
|
||||||
// v0.12.0 — right Jobs & Market pane against the live origin: open packages render with
|
// v0.12.0 — right Jobs & Market pane against the live origin: open packages render with
|
||||||
// names/reward/deadline and Load (UI click) binds one to the starter; the on-board list shows
|
// names/reward/deadline and Load (UI click) binds one to the starter; the on-board list
|
||||||
// loaded packages with fly-to-destination + abandon buttons (penalty preview from the same
|
// (moved to the left pane in v0.20.0, ISS-021) shows loaded packages with fly-to-destination +
|
||||||
// formula as the server); flying planes show their current leg; market buy/sell/refuel previews
|
// abandon buttons (penalty preview from the same
|
||||||
// match the catalog + economy constants exposed in /api/state. Packages are created via
|
// formula as the server); flying planes show their current leg; market buy/sell previews match
|
||||||
|
// the catalog + economy constants exposed in /api/state, and the Refuel-to-full row (moved to the
|
||||||
|
// left pane in v0.23.0, ISS-035) deducts exactly its cost. Packages are created via
|
||||||
// POST /api/test/create-package (FLIGHT_TEST_HOOKS=1), same pattern as e2e/actions.spec.ts.
|
// POST /api/test/create-package (FLIGHT_TEST_HOOKS=1), same pattern as e2e/actions.spec.ts.
|
||||||
|
|
||||||
const SCALE = 1000; // fastest sim speed (v0.14.0 ladder top) — keeps flights to seconds of real time
|
const SCALE = 1000; // fastest sim speed (v0.14.0 ladder top) — keeps flights to seconds of real time
|
||||||
@@ -26,7 +28,7 @@ interface PackageState {
|
|||||||
originName: string;
|
originName: string;
|
||||||
destName: string;
|
destName: string;
|
||||||
reward: number;
|
reward: number;
|
||||||
status: 'open' | 'loaded' | 'delivered' | 'expired' | 'abandoned';
|
status: 'open' | 'loaded' | 'delivered' | 'expired' | 'abandoned' | 'ignored'; // v0.29.0 (ISS-047 part B)
|
||||||
planeId: string | null;
|
planeId: string | null;
|
||||||
createdSimTime: number;
|
createdSimTime: number;
|
||||||
deadlineSimTime: number;
|
deadlineSimTime: number;
|
||||||
@@ -38,8 +40,9 @@ interface CatalogEntry {
|
|||||||
price: number;
|
price: number;
|
||||||
maxFuel: number;
|
maxFuel: number;
|
||||||
burnPerKm: number;
|
burnPerKm: number;
|
||||||
|
emptyWeightKg: number; // v0.16.0 weighted burn input
|
||||||
speedKmh: number;
|
speedKmh: number;
|
||||||
capacity: number;
|
maxPayloadKg: number; // v0.27.0 — replaces the v0.12.0 slot capacity
|
||||||
}
|
}
|
||||||
|
|
||||||
interface StateBody {
|
interface StateBody {
|
||||||
@@ -66,9 +69,10 @@ async function postSim(page: Page, body: unknown) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Set the time scale and VERIFY from the response that it stuck — a silent reset would
|
// Set the time scale and VERIFY from the response that it stuck — a silent reset would
|
||||||
// otherwise surface as an unexplained landing-wait timeout.
|
// otherwise surface as an unexplained landing-wait timeout. ISS-041 also clears pause: a
|
||||||
|
// landing pauses the sim, so any fast-forward after one must resume it or the clock stays frozen.
|
||||||
async function setScale(page: Page, scale: number): Promise<void> {
|
async function setScale(page: Page, scale: number): Promise<void> {
|
||||||
const res = await page.request.post('/api/sim', { data: { timeScale: scale } });
|
const res = await page.request.post('/api/sim', { data: { timeScale: scale, paused: false } });
|
||||||
expect(res.status()).toBe(200);
|
expect(res.status()).toBe(200);
|
||||||
const body = (await res.json()) as { timeScale: number };
|
const body = (await res.json()) as { timeScale: number };
|
||||||
expect(body.timeScale, `timeScale should be ${scale} after POST /api/sim`).toBe(scale);
|
expect(body.timeScale, `timeScale should be ${scale} after POST /api/sim`).toBe(scale);
|
||||||
@@ -114,6 +118,45 @@ async function nearestToHub(page: Page): Promise<{ icao: string; lat: number; lo
|
|||||||
return nearest;
|
return nearest;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Farthest airport from EDDF whose leg still FITS A FULL TANK — the longest flyable leg (v0.16.0
|
||||||
|
// refuel-for-flight test). The dataset's absolute farthest can exceed the aircraft's range (UNNT is
|
||||||
|
// ~4803 km out and needs ~6955 L > the 6300 L tank), so a full-tank fly there would rightly 409;
|
||||||
|
// this test wants a long-but-flyable leg instead.
|
||||||
|
async function farthestFlyableToHub(
|
||||||
|
page: Page,
|
||||||
|
entry: CatalogEntry,
|
||||||
|
): Promise<{ icao: string; lat: number; lon: number; hubLat: number; hubLon: number }> {
|
||||||
|
const fc = (await (await page.request.get('/api/airports')).json()) as {
|
||||||
|
features: Array<{ properties: { icao: string; lat: number; lon: number } }>;
|
||||||
|
};
|
||||||
|
const hub = fc.features.find((f) => f.properties.icao === HUB)!.properties;
|
||||||
|
let farthest: { icao: string; lat: number; lon: number; d: number } | null = null;
|
||||||
|
for (const f of fc.features) {
|
||||||
|
if (f.properties.icao === HUB) continue;
|
||||||
|
const d = haversineKm(hub.lat, hub.lon, f.properties.lat, f.properties.lon);
|
||||||
|
if (requiredFuelFor(entry.burnPerKm, entry.emptyWeightKg, entry.maxFuel, d) > entry.maxFuel) continue; // beyond range
|
||||||
|
if (!farthest || d > farthest.d) {
|
||||||
|
farthest = { icao: f.properties.icao, lat: f.properties.lat, lon: f.properties.lon, d };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!farthest) throw new Error('no full-tank-flyable airport found in the dataset');
|
||||||
|
return { ...farthest, hubLat: hub.lat, hubLon: hub.lon };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mirrors lib/sim/movement.ts (v0.16.0): fuel required to cover distanceKm arriving empty —
|
||||||
|
// closed form of the weight-proportional burn model, k calibrated so a full tank burns burnPerKm.
|
||||||
|
const FUEL_DENSITY_KG_PER_L = 0.8; // must match FUEL_DENSITY_KG_PER_L in lib/sim/movement.ts
|
||||||
|
function requiredFuelFor(burnPerKm: number, emptyWeightKg: number, maxFuel: number, distanceKm: number): number {
|
||||||
|
const k = burnPerKm / (emptyWeightKg + FUEL_DENSITY_KG_PER_L * maxFuel);
|
||||||
|
return (emptyWeightKg / FUEL_DENSITY_KG_PER_L) * (Math.exp(k * FUEL_DENSITY_KG_PER_L * distanceKm) - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mirrors maxRangeKm in lib/sim/movement.ts (v0.28.0): full-tank range under the weighted model.
|
||||||
|
function maxRangeKm(burnPerKm: number, emptyWeightKg: number, maxFuel: number): number {
|
||||||
|
const rho = FUEL_DENSITY_KG_PER_L;
|
||||||
|
return Math.log(1 + (rho * maxFuel) / emptyWeightKg) * ((emptyWeightKg + rho * maxFuel) / (rho * burnPerKm));
|
||||||
|
}
|
||||||
|
|
||||||
// Test hook (FLIGHT_TEST_HOOKS=1): create an open package on a known route.
|
// Test hook (FLIGHT_TEST_HOOKS=1): create an open package on a known route.
|
||||||
async function createPackage(page: Page, fromIcao: string, toIcao: string, deadlineOffsetMs?: number): Promise<PackageState> {
|
async function createPackage(page: Page, fromIcao: string, toIcao: string, deadlineOffsetMs?: number): Promise<PackageState> {
|
||||||
const created = await page.request.post('/api/test/create-package', {
|
const created = await page.request.post('/api/test/create-package', {
|
||||||
@@ -140,6 +183,9 @@ async function flyHomeViaApi(page: Page): Promise<void> {
|
|||||||
.toBe(true);
|
.toBe(true);
|
||||||
}
|
}
|
||||||
if (starter.locationIcao !== HUB) {
|
if (starter.locationIcao !== HUB) {
|
||||||
|
// ISS-041: the landing above paused the sim — setScale clears pause so the return leg
|
||||||
|
// fast-forwards instead of taking real-time hours.
|
||||||
|
await setScale(page, SCALE);
|
||||||
const res = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
const res = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||||
expect(res.status()).toBe(200); // repositioning needs no package (v0.12.0 manual flight)
|
expect(res.status()).toBe(200); // repositioning needs no package (v0.12.0 manual flight)
|
||||||
await expect
|
await expect
|
||||||
@@ -250,6 +296,8 @@ test('on-board list: fly-to-destination + abandon with penalty preview; flying p
|
|||||||
await expect(onboardRow).not.toBeVisible({ timeout: 15_000 });
|
await expect(onboardRow).not.toBeVisible({ timeout: 15_000 });
|
||||||
|
|
||||||
// Restore: fly home so the live instance stays in its onboarding state for the next run.
|
// Restore: fly home so the live instance stays in its onboarding state for the next run.
|
||||||
|
// ISS-041: the arrival above paused the sim, so re-set SCALE for this leg (setScale clears pause).
|
||||||
|
await setScale(page, SCALE);
|
||||||
const homeRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
const homeRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||||
expect(homeRes.status()).toBe(200);
|
expect(homeRes.status()).toBe(200);
|
||||||
await expect
|
await expect
|
||||||
@@ -260,16 +308,19 @@ test('on-board list: fly-to-destination + abandon with penalty preview; flying p
|
|||||||
.toBe(true);
|
.toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('market buy/sell/refuel render with previews from the catalog in /api/state; refuel deducts exactly', async ({ page }) => {
|
test('market buy/sell render with previews from the catalog in /api/state; left-pane Refuel deducts exactly', async ({ page }) => {
|
||||||
test.setTimeout(300_000); // self-heal can take minutes after an interrupted run
|
test.setTimeout(300_000); // self-heal can take minutes after an interrupted run
|
||||||
await flyHomeViaApi(page); // grounded starter at EDDF (tank partial after the previous test's flight)
|
await flyHomeViaApi(page); // grounded starter at EDDF (tank partial after the previous test's flight)
|
||||||
|
|
||||||
const body = await getState(page); // authoritative catalog + economy constants (v0.10.0)
|
const body = await getState(page); // authoritative catalog + economy constants (v0.10.0)
|
||||||
expect(body.catalog.length).toBeGreaterThan(0);
|
expect(body.catalog.length).toBeGreaterThan(0);
|
||||||
const entry = body.catalog.find((e) => e.model === 'atr72')!;
|
const entry = body.catalog.find((e) => e.model === 'atr72')!;
|
||||||
expect(entry.capacity).toBe(6); // v0.12.0 slot capacity exposed in the snapshot
|
expect(entry.maxPayloadKg).toBe(4_800); // ATR 72-600 max payload (lib/game/catalog.ts)
|
||||||
|
|
||||||
await page.goto('/');
|
await page.goto('/');
|
||||||
|
// v0.28.0 (ISS-047): the market rows live in the Planes market tab — switch to it first.
|
||||||
|
await page.getByTestId('tab-planes-market').click();
|
||||||
|
|
||||||
// Buy: the model picker lists the catalog entry and the price preview is its full price.
|
// Buy: the model picker lists the catalog entry and the price preview is its full price.
|
||||||
const buyModel = page.getByTestId('market-buy-model');
|
const buyModel = page.getByTestId('market-buy-model');
|
||||||
await expect(buyModel).toBeVisible({ timeout: 15_000 });
|
await expect(buyModel).toBeVisible({ timeout: 15_000 });
|
||||||
@@ -285,6 +336,9 @@ test('market buy/sell/refuel render with previews from the catalog in /api/state
|
|||||||
const payout = Math.round(entry.price * body.sellFraction * 100) / 100;
|
const payout = Math.round(entry.price * body.sellFraction * 100) / 100;
|
||||||
await expect(page.getByTestId('market-sell-payout')).toContainText(eur(payout));
|
await expect(page.getByTestId('market-sell-payout')).toContainText(eur(payout));
|
||||||
|
|
||||||
|
// ISS-035 (v0.23.0): the Refuel-to-full row now lives in the LEFT pane next to Relocate — same global testids.
|
||||||
|
await expect(page.getByTestId('left-pane').getByTestId('market-refuel')).toBeVisible({ timeout: 15_000 });
|
||||||
|
|
||||||
// Refuel through the pane: the flight genuinely burned fuel…
|
// Refuel through the pane: the flight genuinely burned fuel…
|
||||||
if (starter.fuel < starter.maxFuel) {
|
if (starter.fuel < starter.maxFuel) {
|
||||||
const expectedCost = Math.round((starter.maxFuel - starter.fuel) * body.fuelPricePerL * 100) / 100;
|
const expectedCost = Math.round((starter.maxFuel - starter.fuel) * body.fuelPricePerL * 100) / 100;
|
||||||
@@ -307,3 +361,128 @@ test('market buy/sell/refuel render with previews from the catalog in /api/state
|
|||||||
expect(after.planes.find((p) => p.id === 'plane-starter')!.fuel).toBe(starter.maxFuel);
|
expect(after.planes.find((p) => p.id === 'plane-starter')!.fuel).toBe(starter.maxFuel);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('on-board row Refuel tops up just enough for the package leg; left-pane button says "Refuel to full"', async ({ page }) => {
|
||||||
|
test.setTimeout(300_000); // self-heal + one long flight each way at scale 1000
|
||||||
|
await flyHomeViaApi(page);
|
||||||
|
|
||||||
|
const body = await getState(page);
|
||||||
|
const entry = body.catalog.find((e) => e.model === 'atr72')!;
|
||||||
|
|
||||||
|
// Deterministic baseline: a full tank.
|
||||||
|
expect((await page.request.post('/api/planes/plane-starter/refuel')).status()).toBe(200);
|
||||||
|
|
||||||
|
// Longest FLYABLE leg from the hub (fits a full tank) — long enough that "just enough" for it
|
||||||
|
// exceeds what's left on arrival.
|
||||||
|
const farthest = await farthestFlyableToHub(page, entry);
|
||||||
|
const pkg1 = await createPackage(page, HUB, farthest.icao, 24 * 3_600_000);
|
||||||
|
expect((await page.request.post(`/api/packages/${pkg1.id}/load`, { data: { planeId: 'plane-starter' } })).status()).toBe(200);
|
||||||
|
|
||||||
|
// Fly there (delivers pkg1 on arrival) — the tank is now partial.
|
||||||
|
expect((await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: farthest.icao } })).status()).toBe(200);
|
||||||
|
await setScale(page, SCALE);
|
||||||
|
await expect
|
||||||
|
.poll(async () => {
|
||||||
|
const b = await getState(page);
|
||||||
|
const p = b.planes.find((x) => x.id === 'plane-starter');
|
||||||
|
return !!p && p.status === 'available' && p.locationIcao === farthest.icao;
|
||||||
|
}, { timeout: 240_000, message: `waiting for arrival at ${farthest.icao} (scale 1000)` })
|
||||||
|
.toBe(true);
|
||||||
|
|
||||||
|
// New work at the far end: a package back to the hub — its leg is exactly what we refuel for.
|
||||||
|
const pkg2 = await createPackage(page, farthest.icao, HUB, 24 * 3_600_000);
|
||||||
|
expect((await page.request.post(`/api/packages/${pkg2.id}/load`, { data: { planeId: 'plane-starter' } })).status()).toBe(200);
|
||||||
|
|
||||||
|
// Expected "just enough" from the snapshot constants (mirrors requiredFuelFor in lib/sim/movement.ts).
|
||||||
|
const pre = await getState(page);
|
||||||
|
const fuelBefore = pre.planes.find((p) => p.id === 'plane-starter')!.fuel;
|
||||||
|
const cashBefore = pre.account.cash;
|
||||||
|
const km = haversineKm(farthest.hubLat, farthest.hubLon, farthest.lat, farthest.lon); // symmetric: hub ↔ far end
|
||||||
|
const liters = Math.max(0, requiredFuelFor(entry.burnPerKm, entry.emptyWeightKg, entry.maxFuel, km) - fuelBefore);
|
||||||
|
expect(liters).toBeGreaterThan(0); // the long leg genuinely needs more than what's left
|
||||||
|
const expectedCost = Math.round(liters * pre.fuelPricePerL * 100) / 100;
|
||||||
|
|
||||||
|
await page.goto('/');
|
||||||
|
const refuelBtn = page.getByTestId(`refuel-for-${pkg2.id}`);
|
||||||
|
await expect(refuelBtn, 'row Refuel button appears for the loaded package').toBeVisible({ timeout: 15_000 });
|
||||||
|
// Capture the endpoint's OWN response — the full post-action snapshot at the action's clock.
|
||||||
|
const [res] = await Promise.all([
|
||||||
|
page.waitForResponse((r) => r.url().includes(`/api/planes/plane-starter/refuel`), { timeout: 15_000 }),
|
||||||
|
refuelBtn.click(),
|
||||||
|
]);
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
const post = (await res.json()) as StateBody;
|
||||||
|
|
||||||
|
// Cash dropped by exactly L × price and fuel rose by exactly L.
|
||||||
|
expect(post.account.cash).toBeCloseTo(cashBefore - expectedCost, 6);
|
||||||
|
expect(post.planes.find((p) => p.id === 'plane-starter')!.fuel).toBeCloseTo(fuelBefore + liters, 6);
|
||||||
|
|
||||||
|
// Left pane (moved from the market in v0.23.0, ISS-035): the fill-up button is labeled "Refuel to full" (testid unchanged).
|
||||||
|
await expect(page.getByTestId('market-refuel')).toHaveText('Refuel to full');
|
||||||
|
|
||||||
|
// Restore: fly home — pkg2's destination IS the hub, so it delivers on arrival. The tank holds
|
||||||
|
// exactly the leg requirement, so this also proves "just enough" is enough. ISS-041: the far-end
|
||||||
|
// arrival above paused the sim, so re-set SCALE for this leg (setScale clears pause).
|
||||||
|
await setScale(page, SCALE);
|
||||||
|
expect((await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } })).status()).toBe(200);
|
||||||
|
await expect
|
||||||
|
.poll(async () => (await getState(page)).planes.find((p) => p.id === 'plane-starter')?.locationIcao === HUB, {
|
||||||
|
timeout: 240_000,
|
||||||
|
message: 'waiting for plane-starter to land back at the hub',
|
||||||
|
})
|
||||||
|
.toBe(true);
|
||||||
|
// Top the tank back up so later specs start with a full tank.
|
||||||
|
expect((await page.request.post('/api/planes/plane-starter/refuel')).status()).toBe(200);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Ignore removes an open job from the list permanently (ISS-047 part B)', async ({ page }) => {
|
||||||
|
test.setTimeout(300_000); // self-heal can take minutes after an interrupted run
|
||||||
|
await flyHomeViaApi(page); // deterministic: the starter sits at EDDF
|
||||||
|
|
||||||
|
const nearest = await nearestToHub(page);
|
||||||
|
const pkg = await createPackage(page, HUB, nearest.icao, 24 * 3_600_000);
|
||||||
|
|
||||||
|
await page.goto('/');
|
||||||
|
const row = page.locator(`li[data-testid="open-package-${pkg.id}"]`);
|
||||||
|
await expect(row, 'the hook-created package appears in the list').toBeVisible({ timeout: 15_000 });
|
||||||
|
|
||||||
|
// Ignore through the UI — the post-action snapshot lands immediately (no poll wait).
|
||||||
|
const ignoreBtn = page.getByTestId(`ignore-${pkg.id}`);
|
||||||
|
await expect(ignoreBtn, 'the row has an Ignore button').toBeEnabled();
|
||||||
|
await ignoreBtn.click();
|
||||||
|
|
||||||
|
// Server truth: the package is 'ignored'…
|
||||||
|
await expect
|
||||||
|
.poll(async () => (await getState(page)).packages.find((p) => p.id === pkg.id)?.status, {
|
||||||
|
timeout: 15_000,
|
||||||
|
message: 'waiting for the ignored status in /api/state',
|
||||||
|
})
|
||||||
|
.toBe('ignored');
|
||||||
|
|
||||||
|
// …and the row is gone from the open list (the section filters status==='open').
|
||||||
|
await expect(row).not.toBeVisible({ timeout: 15_000 });
|
||||||
|
|
||||||
|
// A second ignore attempt on the same id is a 409 — 'ignored' is terminal.
|
||||||
|
const again = await page.request.post(`/api/packages/${pkg.id}/ignore`);
|
||||||
|
expect(again.status()).toBe(409);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Planes market tab lists all plane types with tech specs', async ({ page }) => {
|
||||||
|
await page.goto('/');
|
||||||
|
const body = await getState(page); // authoritative catalog — v0.28.0 ships six types
|
||||||
|
expect(body.catalog.length).toBe(6);
|
||||||
|
|
||||||
|
await page.getByTestId('tab-planes-market').click();
|
||||||
|
|
||||||
|
// ATR card: name + full-tank range from the same closed form as lib/sim/movement.ts (v0.28.0).
|
||||||
|
const atr = body.catalog.find((e) => e.model === 'atr72')!;
|
||||||
|
await expect(page.getByTestId('plane-type-atr72'), 'the ATR card appears').toBeVisible({ timeout: 15_000 });
|
||||||
|
await expect(page.getByTestId('plane-type-atr72')).toContainText(atr.label);
|
||||||
|
const atrRange = Math.round(maxRangeKm(atr.burnPerKm, atr.emptyWeightKg, atr.maxFuel));
|
||||||
|
await expect(page.getByTestId('plane-type-range-atr72')).toContainText(`${atrRange} km`);
|
||||||
|
|
||||||
|
// Ladder sanity: the most expensive type (Boeing 777-300ER) is present with its €9M price.
|
||||||
|
const b777 = page.getByTestId('plane-type-b777');
|
||||||
|
await expect(b777).toBeVisible();
|
||||||
|
await expect(b777).toContainText(eur(9_000_000)); // lib/game/catalog.ts
|
||||||
|
});
|
||||||
|
|||||||
@@ -0,0 +1,139 @@
|
|||||||
|
import type { Page } from '@playwright/test';
|
||||||
|
import { expect, test } from '@playwright/test';
|
||||||
|
|
||||||
|
// v0.30.0 — ISS-057: when a landing leaves any plane on the ground the sim slows to 1× server-side
|
||||||
|
// WITHOUT pausing (pause is manual-only now), and starting a flight (POST /api/planes/{id}/fly)
|
||||||
|
// restores the last MANUALLY selected speed once no plane remains grounded. The cycle: dispatch at
|
||||||
|
// 1000× → landing slows to 1× → next dispatch (last grounded plane airborne) resumes 1000×.
|
||||||
|
|
||||||
|
const SCALE = 1000; // fastest sim speed — top of the v0.14.0 ladder (same convention as e2e/sim.spec.ts)
|
||||||
|
const HUB = 'EDDF'; // Frankfurt Main — the seeded starter plane's home base (lib/game/seed.ts)
|
||||||
|
|
||||||
|
interface SimState {
|
||||||
|
clockMs: number;
|
||||||
|
timeScale: number;
|
||||||
|
paused: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface StateBody {
|
||||||
|
simState: SimState;
|
||||||
|
planes: Array<{ id: string; status: string; locationIcao: string; destIcao: string | null }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getState(page: Page): Promise<StateBody> {
|
||||||
|
const res = await page.request.get('/api/state');
|
||||||
|
expect(res.ok()).toBeTruthy();
|
||||||
|
return (await res.json()) as StateBody;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function postSim(page: Page, body: Record<string, unknown>): Promise<void> {
|
||||||
|
const res = await page.request.post('/api/sim', { data: body });
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set the time scale and VERIFY from the response that it stuck — if something external ever
|
||||||
|
// resets the live instance's controls mid-test, fail loudly here instead of timing out later.
|
||||||
|
// ISS-057 also records this as lastSelectedTimeScale (the resume target) and clears pause, so any
|
||||||
|
// fast-forward after a manual pause or a slowed-to-1× landing proceeds at full speed.
|
||||||
|
async function setScale(page: Page, scale: number): Promise<void> {
|
||||||
|
const res = await page.request.post('/api/sim', { data: { timeScale: scale, paused: false } });
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
const body = (await res.json()) as SimState;
|
||||||
|
expect(body.timeScale, `timeScale should be ${scale} after POST /api/sim`).toBe(scale);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Closest airport to the hub from /api/airports → shortest possible leg (fastest e2e flight).
|
||||||
|
async function nearestToHub(page: Page): Promise<{ icao: string }> {
|
||||||
|
const res = await page.request.get('/api/airports');
|
||||||
|
expect(res.ok()).toBeTruthy();
|
||||||
|
const fc = (await res.json()) as { features: Array<{ properties: { icao: string; lat: number; lon: number } }> };
|
||||||
|
const hub = fc.features.find((f) => f.properties.icao === HUB)!.properties;
|
||||||
|
let nearest = fc.features.filter((f) => f.properties.icao !== HUB)[0].properties;
|
||||||
|
for (const f of fc.features) {
|
||||||
|
if (f.properties.icao === HUB) continue;
|
||||||
|
const d = Math.hypot(f.properties.lat - hub.lat, f.properties.lon - hub.lon);
|
||||||
|
const dn = Math.hypot(nearest.lat - hub.lat, nearest.lon - hub.lon);
|
||||||
|
if (d < dn) nearest = f.properties;
|
||||||
|
}
|
||||||
|
return { icao: nearest.icao };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Self-heal helper (same pattern as e2e/relocation.spec.ts): let any in-flight leg finish and
|
||||||
|
// reposition plane-starter home via the API so every test starts from the canonical state even
|
||||||
|
// after an interrupted previous run.
|
||||||
|
async function flyHomeViaApi(page: Page): Promise<void> {
|
||||||
|
let s = await getState(page);
|
||||||
|
let plane = s.planes.find((p) => p.id === 'plane-starter')!;
|
||||||
|
if (plane.status === 'flying' || plane.locationIcao !== HUB) {
|
||||||
|
// Fast-forward any leftover leg / repositioning flight (~20 s real time worst case at 1000×).
|
||||||
|
await setScale(page, SCALE);
|
||||||
|
}
|
||||||
|
if (plane.status === 'flying') {
|
||||||
|
// Let the in-flight leg finish before repositioning. While flying, locationIcao stays at the
|
||||||
|
// DEPARTURE airport — re-read state after landing before deciding whether a repositioning
|
||||||
|
// flight is needed.
|
||||||
|
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.status), { timeout: 240_000 }).toBe('available');
|
||||||
|
s = await getState(page);
|
||||||
|
plane = s.planes.find((p) => p.id === 'plane-starter')!;
|
||||||
|
}
|
||||||
|
if (plane.locationIcao !== HUB) {
|
||||||
|
// ISS-057: the landing above slowed the sim to 1× — setScale restores 1000× (and records it as
|
||||||
|
// lastSelectedTimeScale) so the return leg fast-forwards instead of taking real-time hours.
|
||||||
|
await setScale(page, SCALE);
|
||||||
|
const res = await page.request.post(`/api/planes/${plane.id}/fly`, { data: { destIcao: HUB } });
|
||||||
|
expect(res.ok()).toBeTruthy(); // repositioning needs no package (v0.12.0 manual flight)
|
||||||
|
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.locationIcao), { timeout: 240_000 }).toBe(HUB);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Self-heal in CLEANUP (afterEach): the test deliberately leaves plane-starter at the far end, so
|
||||||
|
// fast-forward + reposition home here; then restore scale=1 / unpaused for later specs.
|
||||||
|
test.afterEach(async ({ page }) => {
|
||||||
|
await flyHomeViaApi(page);
|
||||||
|
await postSim(page, { timeScale: 1, paused: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
test.describe.configure({ mode: 'serial' }); // shared live DB — order matters within this file
|
||||||
|
|
||||||
|
test('landing slows the sim to 1× without pausing; dispatch restores the last selected speed (ISS-057)', async ({ page }) => {
|
||||||
|
test.setTimeout(300_000); // self-heal (worst case ~20 s at 1000×) + two short legs
|
||||||
|
await flyHomeViaApi(page); // deterministic: the starter sits grounded at EDDF
|
||||||
|
|
||||||
|
const nearest = await nearestToHub(page);
|
||||||
|
|
||||||
|
// Set 1000× via the API and verify it stuck (also records lastSelectedTimeScale=1000).
|
||||||
|
await setScale(page, SCALE);
|
||||||
|
|
||||||
|
// Dispatch plane-starter on the shortest leg from its hub (repositioning — no package needed).
|
||||||
|
const flyRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: nearest.icao } });
|
||||||
|
expect(flyRes.status()).toBe(200);
|
||||||
|
|
||||||
|
// Wait for the landing…
|
||||||
|
let landedBody: StateBody | undefined;
|
||||||
|
await expect
|
||||||
|
.poll(async () => {
|
||||||
|
const b = await getState(page);
|
||||||
|
const p = b.planes.find((x) => x.id === 'plane-starter')!;
|
||||||
|
if (p.status === 'available' && p.locationIcao === nearest.icao) landedBody = b;
|
||||||
|
return !!landedBody;
|
||||||
|
}, { timeout: 120_000, message: `waiting for plane-starter to land at ${nearest.icao}` })
|
||||||
|
.toBe(true);
|
||||||
|
|
||||||
|
// …and the server slowed the sim to 1× WITHOUT pausing — persisted on sim_state, so this very
|
||||||
|
// snapshot shows it (the just-landed plane is on ground → slow; ISS-057).
|
||||||
|
expect(landedBody!.simState.paused).toBe(false);
|
||||||
|
expect(landedBody!.simState.timeScale).toBe(1);
|
||||||
|
|
||||||
|
// A subsequent /fly dispatch restores the last selected speed — asserted on the endpoint's OWN
|
||||||
|
// full post-action snapshot, so no poll race with the client's next tick. setScale posted 1000
|
||||||
|
// above, so lastSelectedTimeScale is 1000 and this dispatch (sole grounded plane → airborne)
|
||||||
|
// resumes it.
|
||||||
|
const fly2 = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||||
|
expect(fly2.status()).toBe(200);
|
||||||
|
const resumedBody = (await fly2.json()) as StateBody;
|
||||||
|
expect(resumedBody.simState.paused).toBe(false); // dispatch still clears a manual pause…
|
||||||
|
expect(resumedBody.simState.timeScale).toBe(SCALE); // …and restores the last selected speed
|
||||||
|
|
||||||
|
// Let the return leg finish so cleanup starts from a grounded plane.
|
||||||
|
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.status), { timeout: 120_000 }).toBe('available');
|
||||||
|
});
|
||||||
+1
-1
@@ -36,7 +36,7 @@ test('GET /api/state returns a seeded snapshot', async ({ page }) => {
|
|||||||
|
|
||||||
expect(Array.isArray(body.packages)).toBe(true);
|
expect(Array.isArray(body.packages)).toBe(true);
|
||||||
expect(body.packages.length).toBeGreaterThan(0);
|
expect(body.packages.length).toBeGreaterThan(0);
|
||||||
for (const key of ['id', 'originIcao', 'destIcao', 'reward', 'cargoType', 'deadlineSimTime', 'status']) {
|
for (const key of ['id', 'originIcao', 'destIcao', 'reward', 'cargoType', 'weightKg', 'deadlineSimTime', 'status']) {
|
||||||
expect(body.packages[0], `package.${key}`).toHaveProperty(key);
|
expect(body.packages[0], `package.${key}`).toHaveProperty(key);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import type { Page } from '@playwright/test';
|
||||||
|
import { expect, test } from '@playwright/test';
|
||||||
|
|
||||||
|
// v0.17.0 — ISS-008: action errors surface as toasts at the map's right edge (clear of the
|
||||||
|
// right pane, in addition to the inline pane error) and game events appear as info toasts via
|
||||||
|
// snapshot diffing; the left-pane Time section offers an explicit "Enable notifications" opt-in
|
||||||
|
// for browser notifications.
|
||||||
|
|
||||||
|
interface CatalogEntry {
|
||||||
|
model: string;
|
||||||
|
label: string;
|
||||||
|
price: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface StateBody {
|
||||||
|
account: { cash: number };
|
||||||
|
catalog: CatalogEntry[];
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getState(page: Page): Promise<StateBody> {
|
||||||
|
const res = await page.request.get('/api/state');
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
return (await res.json()) as StateBody;
|
||||||
|
}
|
||||||
|
|
||||||
|
test('failed actions toast at the map right edge, clear of the right pane (inline error stays), and the Time section offers a notifications opt-in', async ({ page }) => {
|
||||||
|
await page.goto('/');
|
||||||
|
// v0.28.0 (ISS-047): the market rows live in the Planes market tab — switch to it first.
|
||||||
|
await page.getByTestId('tab-planes-market').click();
|
||||||
|
|
||||||
|
const buyModel = page.getByTestId('market-buy-model');
|
||||||
|
await expect(buyModel, 'the market section renders once the first snapshot lands').toBeVisible({ timeout: 15_000 });
|
||||||
|
|
||||||
|
// Part A — deterministic error path: the most expensive catalog model (ATR 72-600, €200k) is
|
||||||
|
// unaffordable with starting cash (€20k). On a long-lived local instance cash may have grown
|
||||||
|
// past it — then this part is skipped in place; CI's isolated stack always starts fresh.
|
||||||
|
const body = await getState(page);
|
||||||
|
const priciest = [...body.catalog].sort((a, b) => b.price - a.price)[0];
|
||||||
|
if (body.account.cash < priciest.price) {
|
||||||
|
await buyModel.selectOption(priciest.model);
|
||||||
|
await page.getByTestId('market-buy').click();
|
||||||
|
|
||||||
|
// The toast appears with the server's error message and the error variant class…
|
||||||
|
const toast = page.locator('[data-testid="toast"]').filter({ hasText: /insufficient funds/i });
|
||||||
|
await expect(toast, 'the error toast appears at the map right edge').toBeVisible({ timeout: 10_000 });
|
||||||
|
await expect(toast).toHaveClass(/toast-error/);
|
||||||
|
|
||||||
|
// …and the inline pane error still shows (both surfaces by design). It auto-clears on the
|
||||||
|
// next poll (~1 s), so assert right after the toast — both are set in the same commit.
|
||||||
|
await expect(page.getByTestId('right-error')).toContainText(/insufficient funds/);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Part B — notifications opt-in in the Time section.
|
||||||
|
const btn = page.getByTestId('enable-notifications');
|
||||||
|
await expect(btn, 'the notifications button renders in the Time section').toBeVisible({ timeout: 15_000 });
|
||||||
|
|
||||||
|
// Browsers without the Notification API: disabled with a tooltip-ish title.
|
||||||
|
const supported = await page.evaluate(() => 'Notification' in window);
|
||||||
|
if (!supported) {
|
||||||
|
await expect(btn).toBeDisabled();
|
||||||
|
await expect(btn).toHaveAttribute('title', /does not support/i);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Branch on the ACTUAL permission state — headless CI reports 'denied' (not 'default'), so a
|
||||||
|
// fresh context is not guaranteed to show the opt-in prompt (CI run #47).
|
||||||
|
const permission = await page.evaluate(() => Notification.permission);
|
||||||
|
if (permission === 'denied') {
|
||||||
|
// LeftPane renders the blocked-state label without any click.
|
||||||
|
await expect(btn, 'denied context shows the blocked-state label').toHaveText('Notifications blocked', { timeout: 10_000 });
|
||||||
|
} else if (permission === 'granted') {
|
||||||
|
await expect(btn, 'pre-granted context shows the enabled label').toHaveText('Notifications enabled', { timeout: 10_000 });
|
||||||
|
} else {
|
||||||
|
// 'default' — the opt-in prompt. Clicking requests it; headless may deny, so accept either
|
||||||
|
// outcome, but the label must CHANGE from the prompt to reflect the result.
|
||||||
|
await expect(btn, 'non-denied context shows the opt-in prompt').toHaveText('Enable notifications', { timeout: 10_000 });
|
||||||
|
await btn.click();
|
||||||
|
await expect(btn).not.toHaveText('Enable notifications', { timeout: 10_000 });
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -151,7 +151,8 @@ describe('openGameDb', () => {
|
|||||||
raw.exec(LEGACY_DDL);
|
raw.exec(LEGACY_DDL);
|
||||||
raw.exec(`INSERT INTO planes VALUES ('plane-starter', 'atr72', 'available', 6300, 6300, 'EDDF', NULL, 50.03, 8.57)`);
|
raw.exec(`INSERT INTO planes VALUES ('plane-starter', 'atr72', 'available', 6300, 6300, 'EDDF', NULL, 50.03, 8.57)`);
|
||||||
raw.exec(`INSERT INTO account VALUES (20000, 10)`);
|
raw.exec(`INSERT INTO account VALUES (20000, 10)`);
|
||||||
raw.exec('INSERT INTO sim_state VALUES (1750000000000, 1, 0)');
|
// time_scale = 50 on purpose: the v0.30.0 backfill must copy it into last_selected_time_scale.
|
||||||
|
raw.exec('INSERT INTO sim_state VALUES (1750000000000, 50, 0)');
|
||||||
const file = path.join(dir, 'legacy.db');
|
const file = path.join(dir, 'legacy.db');
|
||||||
await fs.writeFile(file, Buffer.from(raw.export()));
|
await fs.writeFile(file, Buffer.from(raw.export()));
|
||||||
|
|
||||||
@@ -167,6 +168,9 @@ describe('openGameDb', () => {
|
|||||||
// …and the ALTER-default 0 was fixed up to a real timestamp so the first
|
// …and the ALTER-default 0 was fixed up to a real timestamp so the first
|
||||||
// tick-on-read resumes cleanly instead of taking one clamped catch-up jump.
|
// tick-on-read resumes cleanly instead of taking one clamped catch-up jump.
|
||||||
expect(sim?.lastRealTickMs).toBeGreaterThan(0);
|
expect(sim?.lastRealTickMs).toBeGreaterThan(0);
|
||||||
|
// v0.30.0 (ISS-057): the new column backfilled to the legacy row's OWN speed, not the default.
|
||||||
|
expect(sim?.timeScale).toBe(50);
|
||||||
|
expect(sim?.lastSelectedTimeScale).toBe(50);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('migrates a pre-v0.12.0 database: wipes contracts, grounds planes, preserves account + clock', async () => {
|
it('migrates a pre-v0.12.0 database: wipes contracts, grounds planes, preserves account + clock', async () => {
|
||||||
|
|||||||
+22
-3
@@ -30,7 +30,8 @@ CREATE TABLE IF NOT EXISTS planes (
|
|||||||
dest_icao TEXT,
|
dest_icao TEXT,
|
||||||
lat REAL NOT NULL,
|
lat REAL NOT NULL,
|
||||||
lon REAL NOT NULL,
|
lon REAL NOT NULL,
|
||||||
departure_sim_time INTEGER
|
departure_sim_time INTEGER,
|
||||||
|
queue TEXT NOT NULL DEFAULT '[]'
|
||||||
);
|
);
|
||||||
CREATE TABLE IF NOT EXISTS packages (
|
CREATE TABLE IF NOT EXISTS packages (
|
||||||
id TEXT PRIMARY KEY NOT NULL,
|
id TEXT PRIMARY KEY NOT NULL,
|
||||||
@@ -39,6 +40,7 @@ CREATE TABLE IF NOT EXISTS packages (
|
|||||||
reward REAL NOT NULL,
|
reward REAL NOT NULL,
|
||||||
cargo_type TEXT NOT NULL,
|
cargo_type TEXT NOT NULL,
|
||||||
cargo_count INTEGER NOT NULL,
|
cargo_count INTEGER NOT NULL,
|
||||||
|
weight_kg REAL NOT NULL DEFAULT 2000,
|
||||||
deadline_sim_time INTEGER NOT NULL,
|
deadline_sim_time INTEGER NOT NULL,
|
||||||
status TEXT NOT NULL,
|
status TEXT NOT NULL,
|
||||||
plane_id TEXT,
|
plane_id TEXT,
|
||||||
@@ -52,7 +54,8 @@ CREATE TABLE IF NOT EXISTS sim_state (
|
|||||||
clock_ms INTEGER NOT NULL,
|
clock_ms INTEGER NOT NULL,
|
||||||
time_scale REAL NOT NULL,
|
time_scale REAL NOT NULL,
|
||||||
paused INTEGER NOT NULL,
|
paused INTEGER NOT NULL,
|
||||||
last_real_tick_ms INTEGER NOT NULL DEFAULT 0
|
last_real_tick_ms INTEGER NOT NULL DEFAULT 0,
|
||||||
|
last_selected_time_scale REAL NOT NULL DEFAULT 1
|
||||||
);
|
);
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -72,6 +75,20 @@ function migrateColumns(raw: RawSqlJsDatabase): void {
|
|||||||
if (!cols('planes').has('dest_icao')) {
|
if (!cols('planes').has('dest_icao')) {
|
||||||
raw.exec('ALTER TABLE planes ADD COLUMN dest_icao TEXT');
|
raw.exec('ALTER TABLE planes ADD COLUMN dest_icao TEXT');
|
||||||
}
|
}
|
||||||
|
// v0.25.0 (ISS-043): the flight queue — ordered JSON array of not-yet-started leg ICACs.
|
||||||
|
if (!cols('planes').has('queue')) {
|
||||||
|
raw.exec(`ALTER TABLE planes ADD COLUMN queue TEXT NOT NULL DEFAULT '[]'`);
|
||||||
|
}
|
||||||
|
// v0.27.0 (ISS-045): package weight — pre-existing rows backfill to a mid-range default.
|
||||||
|
if (!cols('packages').has('weight_kg')) {
|
||||||
|
raw.exec('ALTER TABLE packages ADD COLUMN weight_kg REAL NOT NULL DEFAULT 2000');
|
||||||
|
}
|
||||||
|
// v0.30.0 (ISS-057): last-selected speed — pre-existing rows backfill to the row's OWN
|
||||||
|
// current time_scale so a legacy DB resumes at the speed it was running, not the default.
|
||||||
|
if (!cols('sim_state').has('last_selected_time_scale')) {
|
||||||
|
raw.exec('ALTER TABLE sim_state ADD COLUMN last_selected_time_scale REAL NOT NULL DEFAULT 1');
|
||||||
|
raw.exec('UPDATE sim_state SET last_selected_time_scale = time_scale');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// v0.12.0 one-time migration: contracts world → packages world. Detected by the
|
// v0.12.0 one-time migration: contracts world → packages world. Detected by the
|
||||||
@@ -159,7 +176,9 @@ async function seedEmpty(instance: GameDb): Promise<void> {
|
|||||||
const rng = mulberry32(randomInt(0, 2 ** 31));
|
const rng = mulberry32(randomInt(0, 2 ** 31));
|
||||||
const data = buildSeed({ airports, rng, nowMs: Date.now() });
|
const data = buildSeed({ airports, rng, nowMs: Date.now() });
|
||||||
|
|
||||||
await instance.db.insert(schema.planes).values(data.plane);
|
// SeedPlane.queue is a string[]; the column stores it as JSON text.
|
||||||
|
const { queue, ...planeCols } = data.plane;
|
||||||
|
await instance.db.insert(schema.planes).values({ ...planeCols, queue: JSON.stringify(queue ?? []) });
|
||||||
await instance.db.insert(schema.packages).values(data.packages);
|
await instance.db.insert(schema.packages).values(data.packages);
|
||||||
await instance.db.insert(schema.account).values(data.account);
|
await instance.db.insert(schema.account).values(data.account);
|
||||||
await instance.db.insert(schema.simState).values(data.simState);
|
await instance.db.insert(schema.simState).values(data.simState);
|
||||||
|
|||||||
+13
-1
@@ -20,6 +20,10 @@ export const planes = sqliteTable('planes', {
|
|||||||
// flying, `fuel` is frozen at its departure value — live position/fuel are pure
|
// flying, `fuel` is frozen at its departure value — live position/fuel are pure
|
||||||
// functions of the clock (lib/sim/movement.ts), recomputed on read.
|
// functions of the clock (lib/sim/movement.ts), recomputed on read.
|
||||||
departureSimTime: integer('departure_sim_time'),
|
departureSimTime: integer('departure_sim_time'),
|
||||||
|
// Queue of upcoming legs NOT yet started (v0.25.0, ISS-043) — ordered JSON array
|
||||||
|
// of ICAO strings ('[]' when empty). The ACTIVE leg stays destIcao +
|
||||||
|
// departureSimTime; on landing the engine auto-chains queue[0] if fuel covers it.
|
||||||
|
queue: text('queue').notNull().default('[]'),
|
||||||
});
|
});
|
||||||
|
|
||||||
// Cargo packages (v0.12.0) replace the old contracts table end-to-end: a package
|
// Cargo packages (v0.12.0) replace the old contracts table end-to-end: a package
|
||||||
@@ -33,10 +37,14 @@ export const packages = sqliteTable('packages', {
|
|||||||
reward: real('reward').notNull(),
|
reward: real('reward').notNull(),
|
||||||
cargoType: text('cargo_type').notNull(),
|
cargoType: text('cargo_type').notNull(),
|
||||||
cargoCount: integer('cargo_count').notNull(),
|
cargoCount: integer('cargo_count').notNull(),
|
||||||
|
// Package weight in kg (v0.27.0, ISS-045) — drives load validation (plane payload)
|
||||||
|
// and the per-kg part of the payout. Pre-existing rows backfill to the default.
|
||||||
|
weightKg: real('weight_kg').notNull().default(2000),
|
||||||
deadlineSimTime: integer('deadline_sim_time').notNull(),
|
deadlineSimTime: integer('deadline_sim_time').notNull(),
|
||||||
// 'expired' = an open OR loaded package whose deadline passed on a tick. Loaded
|
// 'expired' = an open OR loaded package whose deadline passed on a tick. Loaded
|
||||||
// expired packages keep occupying their slot, deliver no reward, and abandon free.
|
// expired packages keep occupying their slot, deliver no reward, and abandon free.
|
||||||
status: text('status', { enum: ['open', 'loaded', 'delivered', 'expired', 'abandoned'] }).notNull(),
|
// 'ignored' (v0.29.0, ISS-047 part B) = a dismissed open job — terminal, leaves the market.
|
||||||
|
status: text('status', { enum: ['open', 'loaded', 'delivered', 'expired', 'abandoned', 'ignored'] }).notNull(),
|
||||||
planeId: text('plane_id'),
|
planeId: text('plane_id'),
|
||||||
createdSimTime: integer('created_sim_time').notNull(),
|
createdSimTime: integer('created_sim_time').notNull(),
|
||||||
});
|
});
|
||||||
@@ -53,6 +61,10 @@ export const simState = sqliteTable('sim_state', {
|
|||||||
// Real-time (Date.now()) of the last tick — the tick-on-read engine advances
|
// Real-time (Date.now()) of the last tick — the tick-on-read engine advances
|
||||||
// clockMs by (now - lastRealTickMs) × timeScale, clamped per tick.
|
// clockMs by (now - lastRealTickMs) × timeScale, clamped per tick.
|
||||||
lastRealTickMs: integer('last_real_tick_ms').notNull(),
|
lastRealTickMs: integer('last_real_tick_ms').notNull(),
|
||||||
|
// Last MANUALLY selected speed (v0.30.0, ISS-057) — landings slow the sim to 1× without
|
||||||
|
// touching this; flyPlane restores it when the last grounded plane takes off. Written by
|
||||||
|
// POST /api/sim whenever timeScale is posted; pre-existing rows backfill to time_scale.
|
||||||
|
lastSelectedTimeScale: real('last_selected_time_scale').notNull().default(1),
|
||||||
});
|
});
|
||||||
|
|
||||||
export type PlaneRow = typeof planes.$inferSelect;
|
export type PlaneRow = typeof planes.$inferSelect;
|
||||||
|
|||||||
@@ -0,0 +1,164 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import type { PackageState, PlaneState, StateSnapshot } from './game/state';
|
||||||
|
import { diffSnapshots } from './deriveEvents';
|
||||||
|
|
||||||
|
// ISS-008 (v0.17.0): snapshot-diffing event derivation — pure core of the toast/notification
|
||||||
|
// feature, unit-tested in node like advanceSimClock/fetchState.
|
||||||
|
|
||||||
|
const CATALOG = [
|
||||||
|
{ model: 'atr72', label: 'ATR 72-600', price: 200_000, maxFuel: 6300, burnPerKm: 1.75, emptyWeightKg: 9300, speedKmh: 510, maxPayloadKg: 4800 },
|
||||||
|
];
|
||||||
|
|
||||||
|
const basePlane = (id: string): PlaneState => ({
|
||||||
|
id,
|
||||||
|
model: 'atr72',
|
||||||
|
status: 'available',
|
||||||
|
fuel: 6300,
|
||||||
|
maxFuel: 6300,
|
||||||
|
locationIcao: 'EDDF',
|
||||||
|
locationName: 'Frankfurt',
|
||||||
|
destIcao: null,
|
||||||
|
destName: null,
|
||||||
|
departureSimTime: null,
|
||||||
|
lat: 50.03,
|
||||||
|
lon: 8.56,
|
||||||
|
queue: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
const basePackage = (id: string): PackageState => ({
|
||||||
|
id,
|
||||||
|
originIcao: 'EDDF',
|
||||||
|
originName: 'Frankfurt',
|
||||||
|
destIcao: 'LEMD',
|
||||||
|
destName: 'Madrid–Barajas',
|
||||||
|
reward: 1234.5,
|
||||||
|
cargoType: 'mail',
|
||||||
|
cargoCount: 2,
|
||||||
|
weightKg: 600,
|
||||||
|
deadlineSimTime: 0,
|
||||||
|
status: 'open',
|
||||||
|
planeId: null,
|
||||||
|
createdSimTime: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
const snapshot = (over: Partial<StateSnapshot> = {}): StateSnapshot => ({
|
||||||
|
account: { cash: 20_000, reputation: 10 },
|
||||||
|
simState: { clockMs: 0, timeScale: 1, paused: false },
|
||||||
|
planes: [basePlane('plane-starter')],
|
||||||
|
packages: [],
|
||||||
|
catalog: CATALOG,
|
||||||
|
fuelPricePerL: 0.8,
|
||||||
|
sellFraction: 0.5,
|
||||||
|
...over,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('diffSnapshots', () => {
|
||||||
|
it('returns [] for identical snapshots (only clock/cash drift)', () => {
|
||||||
|
const prev = snapshot();
|
||||||
|
const next = snapshot({ account: { cash: 21_000, reputation: 11 }, simState: { clockMs: 60_000, timeScale: 1, paused: false } });
|
||||||
|
expect(diffSnapshots(prev, next)).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns [] for the first snapshot (no baseline — no "new package" spam on page load)', () => {
|
||||||
|
const next = snapshot({ packages: [basePackage('pkg-1'), basePackage('pkg-2')] });
|
||||||
|
expect(diffSnapshots(null, next)).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('emits a landing event when a plane goes flying → available (new locationName is the arrival)', () => {
|
||||||
|
const prev = snapshot({
|
||||||
|
planes: [
|
||||||
|
{
|
||||||
|
...basePlane('plane-starter'),
|
||||||
|
status: 'flying',
|
||||||
|
destIcao: 'LEMD',
|
||||||
|
destName: 'Madrid–Barajas',
|
||||||
|
departureSimTime: 0,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const next = snapshot({
|
||||||
|
planes: [
|
||||||
|
{ ...basePlane('plane-starter'), locationIcao: 'LEMD', locationName: 'Madrid–Barajas' },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(diffSnapshots(prev, next)).toEqual([
|
||||||
|
{ kind: 'info', message: 'ATR 72-600 landed at Madrid–Barajas' },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('emits a delivery event with the reward when a loaded package is delivered on arrival', () => {
|
||||||
|
const prev = snapshot({ packages: [{ ...basePackage('pkg-1'), status: 'loaded', planeId: 'plane-starter' }] });
|
||||||
|
const next = snapshot({ packages: [{ ...basePackage('pkg-1'), status: 'delivered', planeId: 'plane-starter' }] });
|
||||||
|
expect(diffSnapshots(prev, next)).toEqual([
|
||||||
|
{ kind: 'info', message: 'Package delivered: +€1,234.50' },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('emits an expiry event for open → expired and loaded → expired', () => {
|
||||||
|
const fromOpen = diffSnapshots(
|
||||||
|
snapshot({ packages: [basePackage('pkg-1')] }),
|
||||||
|
snapshot({ packages: [{ ...basePackage('pkg-1'), status: 'expired' }] }),
|
||||||
|
);
|
||||||
|
expect(fromOpen).toEqual([{ kind: 'info', message: 'Package expired: Frankfurt → Madrid–Barajas' }]);
|
||||||
|
|
||||||
|
const fromLoaded = diffSnapshots(
|
||||||
|
snapshot({ packages: [{ ...basePackage('pkg-2'), status: 'loaded', planeId: 'plane-starter' }] }),
|
||||||
|
snapshot({ packages: [{ ...basePackage('pkg-2'), status: 'expired', planeId: 'plane-starter' }] }),
|
||||||
|
);
|
||||||
|
expect(fromLoaded).toEqual([{ kind: 'info', message: 'Package expired: Frankfurt → Madrid–Barajas' }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('emits a new-package event for ids only in the next snapshot', () => {
|
||||||
|
const prev = snapshot({ packages: [basePackage('pkg-1')] });
|
||||||
|
const next = snapshot({ packages: [basePackage('pkg-1'), basePackage('pkg-2')] });
|
||||||
|
expect(diffSnapshots(prev, next)).toEqual([
|
||||||
|
{ kind: 'info', message: 'New package available: Frankfurt → Madrid–Barajas' },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('emits bought/sold events when the plane id set changes (with the model name)', () => {
|
||||||
|
const bought = diffSnapshots(
|
||||||
|
snapshot(),
|
||||||
|
snapshot({ planes: [basePlane('plane-starter'), basePlane('plane-2')] }),
|
||||||
|
);
|
||||||
|
expect(bought).toEqual([{ kind: 'info', message: 'Bought ATR 72-600' }]);
|
||||||
|
|
||||||
|
const sold = diffSnapshots(
|
||||||
|
snapshot({ planes: [basePlane('plane-starter'), basePlane('plane-2')] }),
|
||||||
|
snapshot(),
|
||||||
|
);
|
||||||
|
expect(sold).toEqual([{ kind: 'info', message: 'Sold ATR 72-600' }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reports every transition in one diff (planes first, then packages)', () => {
|
||||||
|
const prev = snapshot({
|
||||||
|
planes: [
|
||||||
|
{ ...basePlane('plane-starter'), status: 'flying', destIcao: 'LEMD', destName: 'Madrid–Barajas' },
|
||||||
|
basePlane('plane-2'),
|
||||||
|
],
|
||||||
|
packages: [{ ...basePackage('pkg-1'), status: 'loaded', planeId: 'plane-starter' }],
|
||||||
|
});
|
||||||
|
const next = snapshot({
|
||||||
|
planes: [
|
||||||
|
{ ...basePlane('plane-starter'), locationIcao: 'LEMD', locationName: 'Madrid–Barajas' },
|
||||||
|
basePlane('plane-3'),
|
||||||
|
],
|
||||||
|
packages: [{ ...basePackage('pkg-1'), status: 'delivered', planeId: 'plane-starter' }],
|
||||||
|
});
|
||||||
|
expect(diffSnapshots(prev, next)).toEqual([
|
||||||
|
{ kind: 'info', message: 'ATR 72-600 landed at Madrid–Barajas' },
|
||||||
|
{ kind: 'info', message: 'Bought ATR 72-600' },
|
||||||
|
{ kind: 'info', message: 'Sold ATR 72-600' },
|
||||||
|
{ kind: 'info', message: 'Package delivered: +€1,234.50' },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignores transitions that are not events (open → loaded, available → flying)', () => {
|
||||||
|
const prev = snapshot({ packages: [basePackage('pkg-1')] });
|
||||||
|
const next = snapshot({
|
||||||
|
planes: [{ ...basePlane('plane-starter'), status: 'flying', destIcao: 'LEMD', destName: 'Madrid–Barajas' }],
|
||||||
|
packages: [{ ...basePackage('pkg-1'), status: 'loaded', planeId: 'plane-starter' }],
|
||||||
|
});
|
||||||
|
expect(diffSnapshots(prev, next)).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import type { StateSnapshot } from './game/state';
|
||||||
|
import { PLANE_TYPES } from './game/catalog';
|
||||||
|
import { formatCash } from './format';
|
||||||
|
|
||||||
|
// ISS-008 (v0.17.0): derive human-readable game events by diffing two consecutive /api/state
|
||||||
|
// snapshots — there is no server event feed, so the client watches for transitions in the
|
||||||
|
// fields it already receives. Pure and unit-tested; the shell calls it once per new snapshot
|
||||||
|
// and turns each result into an info toast (plus a browser notification when hidden).
|
||||||
|
|
||||||
|
export interface GameEvent {
|
||||||
|
kind: 'info';
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const planeName = (model: string): string => PLANE_TYPES[model]?.name ?? model;
|
||||||
|
|
||||||
|
export function diffSnapshots(prev: StateSnapshot | null, next: StateSnapshot): GameEvent[] {
|
||||||
|
// No baseline yet (first snapshot after load) — nothing to compare against. Emitting a
|
||||||
|
// "new package" event for every existing row would spam the stack on page load.
|
||||||
|
if (prev === null) return [];
|
||||||
|
|
||||||
|
const events: GameEvent[] = [];
|
||||||
|
|
||||||
|
// Planes: landed (flying → available, new locationName is the arrival airport), bought or
|
||||||
|
// sold (id set changed — ids are stable for a plane's whole life).
|
||||||
|
const prevPlanes = new Map(prev.planes.map((p) => [p.id, p]));
|
||||||
|
for (const plane of next.planes) {
|
||||||
|
const before = prevPlanes.get(plane.id);
|
||||||
|
if (!before) {
|
||||||
|
events.push({ kind: 'info', message: `Bought ${planeName(plane.model)}` });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (before.status === 'flying' && plane.status === 'available') {
|
||||||
|
events.push({ kind: 'info', message: `${planeName(plane.model)} landed at ${plane.locationName}` });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const [id, before] of prevPlanes) {
|
||||||
|
if (!next.planes.some((p) => p.id === id)) {
|
||||||
|
events.push({ kind: 'info', message: `Sold ${planeName(before.model)}` });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Packages: delivered (loaded → delivered, reward paid out in the same tick), expired
|
||||||
|
// (open|loaded → expired), newly appeared (id only in next — terminal packages are never
|
||||||
|
// deleted, so an id appearing is always a genuinely new one).
|
||||||
|
const prevPackages = new Map(prev.packages.map((p) => [p.id, p]));
|
||||||
|
for (const pkg of next.packages) {
|
||||||
|
const before = prevPackages.get(pkg.id);
|
||||||
|
if (!before) {
|
||||||
|
events.push({ kind: 'info', message: `New package available: ${pkg.originName} → ${pkg.destName}` });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (before.status === 'loaded' && pkg.status === 'delivered') {
|
||||||
|
events.push({ kind: 'info', message: `Package delivered: +${formatCash(pkg.reward)}` });
|
||||||
|
} else if ((before.status === 'open' || before.status === 'loaded') && pkg.status === 'expired') {
|
||||||
|
events.push({ kind: 'info', message: `Package expired: ${pkg.originName} → ${pkg.destName}` });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return events;
|
||||||
|
}
|
||||||
+265
-14
@@ -6,14 +6,19 @@ import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
|||||||
import { openGameDb, type GameDb } from '@/lib/db/client';
|
import { openGameDb, type GameDb } from '@/lib/db/client';
|
||||||
import * as schema from '@/lib/db/schema';
|
import * as schema from '@/lib/db/schema';
|
||||||
import { loadAirportsGeoJson } from '@/lib/airports';
|
import { loadAirportsGeoJson } from '@/lib/airports';
|
||||||
|
import { haversineKm } from '@/lib/geo';
|
||||||
|
import { requiredFuelFor } from '@/lib/sim/movement';
|
||||||
import { FUEL_PRICE_PER_L, PLANE_TYPES, SELL_FRACTION } from './catalog';
|
import { FUEL_PRICE_PER_L, PLANE_TYPES, SELL_FRACTION } from './catalog';
|
||||||
import { HUB_ICAO } from './seed';
|
import { HUB_ICAO } from './seed';
|
||||||
import {
|
import {
|
||||||
abandonPackage,
|
abandonPackage,
|
||||||
buyPlane,
|
buyPlane,
|
||||||
|
cancelQueuedLeg,
|
||||||
flyPlane,
|
flyPlane,
|
||||||
GameActionError,
|
GameActionError,
|
||||||
|
ignorePackage,
|
||||||
loadPackage,
|
loadPackage,
|
||||||
|
queueLeg,
|
||||||
refuelPlane,
|
refuelPlane,
|
||||||
sellPlane,
|
sellPlane,
|
||||||
} from './actions';
|
} from './actions';
|
||||||
@@ -123,27 +128,27 @@ describe('loadPackage', () => {
|
|||||||
await expectActionError(loadPackage(inst, 'p-open', 'plane-starter'), 409, /at LEMD/);
|
await expectActionError(loadPackage(inst, 'p-open', 'plane-starter'), 409, /at LEMD/);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('rejects loading when the plane has no free slot (capacity from catalog)', async () => {
|
it('rejects loading when the plane has no payload room (maxPayloadKg from catalog)', async () => {
|
||||||
const inst = await freshDb('load-full.db');
|
const inst = await freshDb('load-full.db');
|
||||||
await insertOpenPackage(inst, 'p-new');
|
await insertOpenPackage(inst, 'p-new', { weightKg: 1_000 });
|
||||||
// Fill all atr72 slots with loaded cargo…
|
// Fill past maxPayloadKg with loaded cargo…
|
||||||
for (let i = 0; i < PLANE_TYPES.atr72.capacity; i++) {
|
const chunk = Math.floor(PLANE_TYPES.atr72.maxPayloadKg / 3) + 1; // 3 chunks > max
|
||||||
await insertOpenPackage(inst, `p-fill-${i}`, { status: 'loaded', planeId: 'plane-starter' });
|
for (let i = 0; i < 3; i++) {
|
||||||
|
await insertOpenPackage(inst, `p-fill-${i}`, { status: 'loaded', planeId: 'plane-starter', weightKg: chunk });
|
||||||
}
|
}
|
||||||
|
|
||||||
await expectActionError(loadPackage(inst, 'p-new', 'plane-starter'), 409, /no free slots/i);
|
await expectActionError(loadPackage(inst, 'p-new', 'plane-starter'), 409, /no payload room/i);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('counts expired packages as occupying their slot too', async () => {
|
it('counts expired packages as occupying their payload too', async () => {
|
||||||
const inst = await freshDb('load-expiredslot.db');
|
const inst = await freshDb('load-expiredslot.db');
|
||||||
await insertOpenPackage(inst, 'p-new');
|
await insertOpenPackage(inst, 'p-new', { weightKg: 1_000 });
|
||||||
// capacity − 1 loaded + 1 expired = full.
|
// Half + half (expired) leaves no room — each alone would fit.
|
||||||
for (let i = 0; i < PLANE_TYPES.atr72.capacity - 1; i++) {
|
const half = Math.floor(PLANE_TYPES.atr72.maxPayloadKg / 2) + 1;
|
||||||
await insertOpenPackage(inst, `p-fill-${i}`, { status: 'loaded', planeId: 'plane-starter' });
|
await insertOpenPackage(inst, 'p-loaded-half', { status: 'loaded', planeId: 'plane-starter', weightKg: half });
|
||||||
}
|
await insertOpenPackage(inst, 'p-expired-slot', { status: 'expired', planeId: 'plane-starter', weightKg: half });
|
||||||
await insertOpenPackage(inst, 'p-expired-slot', { status: 'expired', planeId: 'plane-starter' });
|
|
||||||
|
|
||||||
await expectActionError(loadPackage(inst, 'p-new', 'plane-starter'), 409, /no free slots/i);
|
await expectActionError(loadPackage(inst, 'p-new', 'plane-starter'), 409, /no payload room/i);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -165,6 +170,34 @@ describe('flyPlane', () => {
|
|||||||
expect(plane.fuel).toBe(PLANE_TYPES.atr72.maxFuel);
|
expect(plane.fuel).toBe(PLANE_TYPES.atr72.maxFuel);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('resumes a manual pause and restores lastSelectedTimeScale when the last grounded plane takes off (ISS-057)', async () => {
|
||||||
|
const inst = await freshDb('fly-resume.db');
|
||||||
|
// A landing slowed the sim to 1×; the player's last manually selected speed was 250.
|
||||||
|
await inst.db.update(schema.simState).set({ paused: true, timeScale: 1, lastSelectedTimeScale: 250 });
|
||||||
|
|
||||||
|
await flyPlane(inst, 'plane-starter', 'LEMD'); // sole grounded plane → airborne
|
||||||
|
|
||||||
|
const sim = (await inst.db.select().from(schema.simState))[0];
|
||||||
|
expect(sim.paused).toBe(false); // dispatch still resumes a manual pause…
|
||||||
|
expect(sim.timeScale).toBe(250); // …and restores the last selected speed
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps 1× when another plane is still grounded after dispatch (ISS-057)', async () => {
|
||||||
|
const inst = await freshDb('fly-stayslow.db');
|
||||||
|
await inst.db.update(schema.simState).set({ timeScale: 1, lastSelectedTimeScale: 250 });
|
||||||
|
// A second grounded plane — the starter taking off leaves it on the ground.
|
||||||
|
await inst.db.insert(schema.planes).values({
|
||||||
|
id: 'plane-extra', model: 'atr72', status: 'available', fuel: 100, maxFuel: PLANE_TYPES.atr72.maxFuel,
|
||||||
|
locationIcao: HUB_ICAO, destIcao: null, lat: 50, lon: 8, departureSimTime: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
await flyPlane(inst, 'plane-starter', 'LEMD');
|
||||||
|
|
||||||
|
const sim = (await inst.db.select().from(schema.simState))[0];
|
||||||
|
expect(sim.paused).toBe(false);
|
||||||
|
expect(sim.timeScale).toBe(1); // another plane on ground → stays slowed
|
||||||
|
});
|
||||||
|
|
||||||
it('rejects a flying plane with 409', async () => {
|
it('rejects a flying plane with 409', async () => {
|
||||||
const inst = await freshDb('fly-flying.db');
|
const inst = await freshDb('fly-flying.db');
|
||||||
await inst.db.update(schema.planes)
|
await inst.db.update(schema.planes)
|
||||||
@@ -192,6 +225,75 @@ describe('flyPlane', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('queueLeg (v0.25.0, ISS-043)', () => {
|
||||||
|
it('appends legs to the queue in order and persists them as JSON', async () => {
|
||||||
|
const inst = await freshDb('qleg-ok.db');
|
||||||
|
|
||||||
|
await queueLeg(inst, 'plane-starter', 'LEMD');
|
||||||
|
let plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
|
expect(JSON.parse(plane.queue)).toEqual(['LEMD']);
|
||||||
|
|
||||||
|
await queueLeg(inst, 'plane-starter', 'EHAM'); // pre-building a route
|
||||||
|
plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
|
expect(JSON.parse(plane.queue)).toEqual(['LEMD', 'EHAM']); // order preserved
|
||||||
|
});
|
||||||
|
|
||||||
|
it('works on a flying plane too — the active leg is untouched, nothing auto-starts', async () => {
|
||||||
|
const inst = await freshDb('qleg-flying.db');
|
||||||
|
await inst.db.update(schema.planes)
|
||||||
|
.set({ status: 'flying', departureSimTime: T0, destIcao: 'LEMD' })
|
||||||
|
.where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
|
await queueLeg(inst, 'plane-starter', 'EHAM');
|
||||||
|
|
||||||
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
|
expect(plane.status).toBe('flying'); // still on its active leg…
|
||||||
|
expect(plane.destIcao).toBe('LEMD'); // …unchanged — queueing never starts a flight
|
||||||
|
expect(JSON.parse(plane.queue)).toEqual(['EHAM']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects an unknown plane id with 404', async () => {
|
||||||
|
const inst = await freshDb('qleg-ghost.db');
|
||||||
|
await expectActionError(queueLeg(inst, 'ghost', 'LEMD'), 404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects an ICAO not in the airport dataset with 400', async () => {
|
||||||
|
const inst = await freshDb('qleg-unknownicao.db');
|
||||||
|
await expectActionError(queueLeg(inst, 'plane-starter', 'ZZZZ'), 400, /unknown airport/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('cancelQueuedLeg (v0.25.0, ISS-043)', () => {
|
||||||
|
it('removes the leg at the given index and keeps the rest in order', async () => {
|
||||||
|
const inst = await freshDb('qcancel-ok.db');
|
||||||
|
await queueLeg(inst, 'plane-starter', 'LEMD');
|
||||||
|
await queueLeg(inst, 'plane-starter', 'EHAM');
|
||||||
|
await queueLeg(inst, 'plane-starter', 'EDDV');
|
||||||
|
|
||||||
|
await cancelQueuedLeg(inst, 'plane-starter', 1); // drop EHAM (the middle leg)
|
||||||
|
|
||||||
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
|
expect(JSON.parse(plane.queue)).toEqual(['LEMD', 'EDDV']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects an out-of-range index with 400', async () => {
|
||||||
|
const inst = await freshDb('qcancel-oob.db');
|
||||||
|
await queueLeg(inst, 'plane-starter', 'LEMD'); // one leg → only index 0 is valid
|
||||||
|
await expectActionError(cancelQueuedLeg(inst, 'plane-starter', 1), 400);
|
||||||
|
await expectActionError(cancelQueuedLeg(inst, 'plane-starter', -1), 400);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects cancelling from an empty queue with 400', async () => {
|
||||||
|
const inst = await freshDb('qcancel-empty.db'); // seeded starter has no queued legs
|
||||||
|
await expectActionError(cancelQueuedLeg(inst, 'plane-starter', 0), 400);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects an unknown plane id with 404', async () => {
|
||||||
|
const inst = await freshDb('qcancel-ghost.db');
|
||||||
|
await expectActionError(cancelQueuedLeg(inst, 'ghost', 0), 404);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('abandonPackage', () => {
|
describe('abandonPackage', () => {
|
||||||
// A loaded package created at T0 with a 10h window; the seeded sim clock is T0.
|
// A loaded package created at T0 with a 10h window; the seeded sim clock is T0.
|
||||||
const REWARD = 1_000;
|
const REWARD = 1_000;
|
||||||
@@ -289,6 +391,36 @@ describe('abandonPackage', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('ignorePackage', () => {
|
||||||
|
it('flips an open package to ignored — no penalty, nothing else changes', async () => {
|
||||||
|
const inst = await freshDb('ig-open.db');
|
||||||
|
await insertOpenPackage(inst, 'p-ig');
|
||||||
|
const cashBefore = (await inst.db.select().from(schema.account))[0].cash;
|
||||||
|
|
||||||
|
await ignorePackage(inst, 'p-ig');
|
||||||
|
|
||||||
|
const row = (await inst.db.select().from(schema.packages).where(eq(schema.packages.id, 'p-ig')))[0];
|
||||||
|
expect(row.status).toBe('ignored');
|
||||||
|
expect(row.planeId).toBeNull(); // was never bound
|
||||||
|
expect((await inst.db.select().from(schema.account))[0].cash).toBe(cashBefore); // no penalty
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(['loaded', 'delivered', 'expired', 'abandoned', 'ignored'] as const)(
|
||||||
|
'rejects a %s package with 409 (must be open)',
|
||||||
|
async (status) => {
|
||||||
|
const inst = await freshDb(`ig-${status}.db`);
|
||||||
|
await insertOpenPackage(inst, 'p-x', { status });
|
||||||
|
|
||||||
|
await expectActionError(ignorePackage(inst, 'p-x'), 409, new RegExp(status));
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it('rejects an unknown id with 404', async () => {
|
||||||
|
const inst = await freshDb('ig-unknown.db');
|
||||||
|
await expectActionError(ignorePackage(inst, 'nope'), 404);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('buyPlane', () => {
|
describe('buyPlane', () => {
|
||||||
it('deducts the full price and delivers a full-tank plane at the home base', async () => {
|
it('deducts the full price and delivers a full-tank plane at the home base', async () => {
|
||||||
const inst = await freshDb('buy-ok.db');
|
const inst = await freshDb('buy-ok.db');
|
||||||
@@ -355,6 +487,19 @@ describe('sellPlane', () => {
|
|||||||
await expectActionError(sellPlane(inst, 'plane-extra'), 409, /flying/);
|
await expectActionError(sellPlane(inst, 'plane-extra'), 409, /flying/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('rejects selling a grounded plane that still carries cargo with 409 (v0.28.0)', async () => {
|
||||||
|
const inst = await freshDb('sell-cargo.db');
|
||||||
|
await inst.db.insert(schema.planes).values({
|
||||||
|
id: 'plane-extra', model: 'atr72', status: 'available', fuel: 100, maxFuel: PLANE_TYPES.atr72.maxFuel,
|
||||||
|
locationIcao: HUB_ICAO, destIcao: null, lat: 50, lon: 8, departureSimTime: null,
|
||||||
|
});
|
||||||
|
await insertOpenPackage(inst, 'p-loaded', { status: 'loaded', planeId: 'plane-extra' });
|
||||||
|
|
||||||
|
await expectActionError(sellPlane(inst, 'plane-extra'), 409, /carrying cargo/);
|
||||||
|
const ids = (await inst.db.select().from(schema.planes)).map((p) => p.id);
|
||||||
|
expect(ids).toContain('plane-extra'); // row untouched — the cargo stays bound to a real plane
|
||||||
|
});
|
||||||
|
|
||||||
it('rejects selling the last remaining plane with 409', async () => {
|
it('rejects selling the last remaining plane with 409', async () => {
|
||||||
const inst = await freshDb('sell-last.db'); // only the starter exists
|
const inst = await freshDb('sell-last.db'); // only the starter exists
|
||||||
await expectActionError(sellPlane(inst, 'plane-starter'), 409, /last remaining/);
|
await expectActionError(sellPlane(inst, 'plane-starter'), 409, /last remaining/);
|
||||||
@@ -412,4 +557,110 @@ describe('refuelPlane', () => {
|
|||||||
const inst = await freshDb('refuel-unknown.db');
|
const inst = await freshDb('refuel-unknown.db');
|
||||||
await expectActionError(refuelPlane(inst, 'ghost'), 404);
|
await expectActionError(refuelPlane(inst, 'ghost'), 404);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// --- forFlight mode (v0.16.0) ---
|
||||||
|
|
||||||
|
it('forFlight adds exactly the liters needed for the package leg and deducts L × price', async () => {
|
||||||
|
const inst = await freshDb('refuel-forflight-ok.db');
|
||||||
|
await insertOpenPackage(inst, 'p-ff', { destIcao: 'LEMD' }); // EDDF → LEMD
|
||||||
|
await loadPackage(inst, 'p-ff', 'plane-starter');
|
||||||
|
|
||||||
|
const fc = await loadAirportsGeoJson();
|
||||||
|
const from = fc.features.find((f) => f.properties.icao === HUB_ICAO)!.properties;
|
||||||
|
const to = fc.features.find((f) => f.properties.icao === 'LEMD')!.properties;
|
||||||
|
const km = haversineKm(from.lat, from.lon, to.lat, to.lon);
|
||||||
|
const type = PLANE_TYPES.atr72;
|
||||||
|
const required = requiredFuelFor(type.burnPerKm, type.emptyWeightKg, type.maxFuel, km);
|
||||||
|
|
||||||
|
// Partial tank below the requirement so L > 0.
|
||||||
|
const startFuel = Math.round(required / 2);
|
||||||
|
await inst.db.update(schema.planes).set({ fuel: startFuel }).where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
const cashBefore = (await inst.db.select().from(schema.account))[0].cash;
|
||||||
|
|
||||||
|
const { cost } = await refuelPlane(inst, 'plane-starter', { mode: 'forFlight', packageId: 'p-ff' });
|
||||||
|
|
||||||
|
expect(cost).toBe(Math.round((required - startFuel) * FUEL_PRICE_PER_L * 100) / 100);
|
||||||
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
|
expect(plane.fuel).toBeCloseTo(required, 6); // topped up to exactly the leg requirement
|
||||||
|
const account = (await inst.db.select().from(schema.account))[0];
|
||||||
|
expect(account.cash).toBeCloseTo(cashBefore - cost, 6);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('forFlight leaves an exactly-feasible tank — flyPlane to the package dest succeeds right after', async () => {
|
||||||
|
const inst = await freshDb('refuel-ff-flyafter.db');
|
||||||
|
await insertOpenPackage(inst, 'p-fa', { destIcao: 'LEMD' }); // EDDF → LEMD
|
||||||
|
await loadPackage(inst, 'p-fa', 'plane-starter');
|
||||||
|
|
||||||
|
const fc = await loadAirportsGeoJson();
|
||||||
|
const from = fc.features.find((f) => f.properties.icao === HUB_ICAO)!.properties;
|
||||||
|
const to = fc.features.find((f) => f.properties.icao === 'LEMD')!.properties;
|
||||||
|
const km = haversineKm(from.lat, from.lon, to.lat, to.lon);
|
||||||
|
const type = PLANE_TYPES.atr72;
|
||||||
|
const required = requiredFuelFor(type.burnPerKm, type.emptyWeightKg, type.maxFuel, km);
|
||||||
|
|
||||||
|
// Empty-ish tank: well below the leg requirement.
|
||||||
|
await inst.db.update(schema.planes).set({ fuel: Math.round(required / 4) }).where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
|
await refuelPlane(inst, 'plane-starter', { mode: 'forFlight', packageId: 'p-fa' });
|
||||||
|
|
||||||
|
// The leg must now be flyable — no epsilon-short 409 (regression guard for the float-exact target).
|
||||||
|
await flyPlane(inst, 'plane-starter', 'LEMD');
|
||||||
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
|
expect(plane.status).toBe('flying');
|
||||||
|
expect(plane.destIcao).toBe('LEMD');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('forFlight is a free no-op when the tank already covers the leg', async () => {
|
||||||
|
const inst = await freshDb('refuel-forflight-enough.db'); // seeded starter is full at EDDF
|
||||||
|
await insertOpenPackage(inst, 'p-ff2', { destIcao: 'LEMD' });
|
||||||
|
await loadPackage(inst, 'p-ff2', 'plane-starter');
|
||||||
|
const cashBefore = (await inst.db.select().from(schema.account))[0].cash;
|
||||||
|
|
||||||
|
const { cost } = await refuelPlane(inst, 'plane-starter', { mode: 'forFlight', packageId: 'p-ff2' });
|
||||||
|
|
||||||
|
expect(cost).toBe(0);
|
||||||
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
|
expect(plane.fuel).toBe(PLANE_TYPES.atr72.maxFuel); // untouched
|
||||||
|
expect((await inst.db.select().from(schema.account))[0].cash).toBe(cashBefore);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('forFlight rejects a package that is not loaded on this plane with 409', async () => {
|
||||||
|
const inst = await freshDb('refuel-ff-open.db'); // open — never loaded
|
||||||
|
await insertOpenPackage(inst, 'p-x');
|
||||||
|
await expectActionError(refuelPlane(inst, 'plane-starter', { mode: 'forFlight', packageId: 'p-x' }), 409);
|
||||||
|
|
||||||
|
const inst2 = await freshDb('refuel-ff-other.db'); // loaded on ANOTHER plane
|
||||||
|
await insertOpenPackage(inst2, 'p-y', { status: 'loaded', planeId: 'plane-someone-else' });
|
||||||
|
await expectActionError(refuelPlane(inst2, 'plane-starter', { mode: 'forFlight', packageId: 'p-y' }), 409);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('forFlight rejects an expired package with 409', async () => {
|
||||||
|
const inst = await freshDb('refuel-ff-expired.db');
|
||||||
|
await insertOpenPackage(inst, 'p-z', { status: 'expired', planeId: 'plane-starter' });
|
||||||
|
await expectActionError(refuelPlane(inst, 'plane-starter', { mode: 'forFlight', packageId: 'p-z' }), 409);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('forFlight rejects an unknown package id with 404', async () => {
|
||||||
|
const inst = await freshDb('refuel-ff-unknown.db');
|
||||||
|
await expectActionError(refuelPlane(inst, 'plane-starter', { mode: 'forFlight', packageId: 'nope' }), 404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('forFlight rejects a missing packageId with 400', async () => {
|
||||||
|
const inst = await freshDb('refuel-ff-nopkg.db');
|
||||||
|
await expectActionError(refuelPlane(inst, 'plane-starter', { mode: 'forFlight' }), 400);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('forFlight rejects a leg that does not fit even a full tank with 409', async () => {
|
||||||
|
const inst = await freshDb('refuel-ff-nofit.db');
|
||||||
|
// UNNT (Narsarsuaq, Greenland) ↔ LPPD are ~7670 km apart — far beyond the ATR's range.
|
||||||
|
await insertOpenPackage(inst, 'p-far', { destIcao: 'LPPD' });
|
||||||
|
await loadPackage(inst, 'p-far', 'plane-starter');
|
||||||
|
await inst.db.update(schema.planes).set({ locationIcao: 'UNNT' }).where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
|
await expectActionError(
|
||||||
|
refuelPlane(inst, 'plane-starter', { mode: 'forFlight', packageId: 'p-far' }),
|
||||||
|
409,
|
||||||
|
/does not fit/i,
|
||||||
|
);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+139
-17
@@ -4,8 +4,9 @@ import * as schema from '@/lib/db/schema';
|
|||||||
import { persist, type GameDb } from '@/lib/db/client';
|
import { persist, type GameDb } from '@/lib/db/client';
|
||||||
import { loadAirportsGeoJson } from '@/lib/airports';
|
import { loadAirportsGeoJson } from '@/lib/airports';
|
||||||
import { haversineKm } from '@/lib/geo';
|
import { haversineKm } from '@/lib/geo';
|
||||||
|
import { requiredFuelFor } from '@/lib/sim/movement';
|
||||||
import { runAction } from '@/lib/sim/engine';
|
import { runAction } from '@/lib/sim/engine';
|
||||||
import { getStateSnapshot } from './state';
|
import { getStateSnapshot, parseIcaoQueue } from './state';
|
||||||
import { FUEL_PRICE_PER_L, PLANE_TYPES, SELL_FRACTION } from './catalog';
|
import { FUEL_PRICE_PER_L, PLANE_TYPES, SELL_FRACTION } from './catalog';
|
||||||
import { abandonPenalty } from './penalty';
|
import { abandonPenalty } from './penalty';
|
||||||
import { HUB_ICAO } from './seed';
|
import { HUB_ICAO } from './seed';
|
||||||
@@ -19,7 +20,7 @@ import { HUB_ICAO } from './seed';
|
|||||||
// GameActionError carrying the HTTP status:
|
// GameActionError carrying the HTTP status:
|
||||||
// 404 — unknown entity id
|
// 404 — unknown entity id
|
||||||
// 409 — valid ids but the current state forbids the action (wrong package/plane
|
// 409 — valid ids but the current state forbids the action (wrong package/plane
|
||||||
// status, plane not at origin, no free slot, insufficient fuel/funds, last plane)
|
// status, plane not at origin, no payload room, insufficient fuel/funds, last plane)
|
||||||
// 400 — bad input that isn't an existence problem (unknown airport/model)
|
// 400 — bad input that isn't an existence problem (unknown airport/model)
|
||||||
|
|
||||||
export class GameActionError extends Error {
|
export class GameActionError extends Error {
|
||||||
@@ -42,8 +43,9 @@ async function airportByIcao(icao: string): Promise<{ icao: string; lat: number;
|
|||||||
// --- Load (POST /api/packages/:id/load {planeId}) ---
|
// --- Load (POST /api/packages/:id/load {planeId}) ---
|
||||||
|
|
||||||
// open → loaded, bound to the plane. The plane must be GROUNDED at the package's
|
// open → loaded, bound to the plane. The plane must be GROUNDED at the package's
|
||||||
// origin with a free slot (slots = packages 'loaded' or 'expired' on it — expired
|
// origin with enough payload room (v0.27.0: used kg = sum of weightKg over packages
|
||||||
// cargo keeps occupying its space until delivered/abandoned).
|
// 'loaded' or 'expired' on it — expired cargo keeps occupying its space until
|
||||||
|
// delivered/abandoned).
|
||||||
export async function loadPackage(inst: GameDb, packageId: string, planeId: string): Promise<void> {
|
export async function loadPackage(inst: GameDb, packageId: string, planeId: string): Promise<void> {
|
||||||
const [pkgRows, planeRows] = await Promise.all([
|
const [pkgRows, planeRows] = await Promise.all([
|
||||||
inst.db.select().from(schema.packages).where(eq(schema.packages.id, packageId)),
|
inst.db.select().from(schema.packages).where(eq(schema.packages.id, packageId)),
|
||||||
@@ -68,13 +70,12 @@ export async function loadPackage(inst: GameDb, packageId: string, planeId: stri
|
|||||||
|
|
||||||
const type = PLANE_TYPES[plane.model];
|
const type = PLANE_TYPES[plane.model];
|
||||||
if (!type) throw new Error(`unknown plane model ${plane.model}`); // → 500, cannot happen for seeded data
|
if (!type) throw new Error(`unknown plane model ${plane.model}`); // → 500, cannot happen for seeded data
|
||||||
const occupied = (
|
const occupied = await inst.db.select({ weightKg: schema.packages.weightKg }).from(schema.packages).where(
|
||||||
await inst.db.select().from(schema.packages).where(
|
|
||||||
and(inArray(schema.packages.status, ['loaded', 'expired']), eq(schema.packages.planeId, plane.id)),
|
and(inArray(schema.packages.status, ['loaded', 'expired']), eq(schema.packages.planeId, plane.id)),
|
||||||
)
|
);
|
||||||
).length;
|
const usedKg = occupied.reduce((sum, r) => sum + (r.weightKg ?? 0), 0);
|
||||||
if (occupied >= type.capacity) {
|
if (usedKg + pkg.weightKg > type.maxPayloadKg) {
|
||||||
throw new GameActionError(409, `no free slots: the ${type.name} carries ${occupied}/${type.capacity} packages`);
|
throw new GameActionError(409, `no payload room: the ${type.name} carries ${Math.round(usedKg)}/${type.maxPayloadKg} kg`);
|
||||||
}
|
}
|
||||||
|
|
||||||
await inst.db.update(schema.packages)
|
await inst.db.update(schema.packages)
|
||||||
@@ -105,9 +106,10 @@ export async function flyPlane(inst: GameDb, planeId: string, destIcao: string):
|
|||||||
const type = PLANE_TYPES[plane.model];
|
const type = PLANE_TYPES[plane.model];
|
||||||
if (!type) throw new Error(`unknown plane model ${plane.model}`); // → 500, cannot happen for seeded data
|
if (!type) throw new Error(`unknown plane model ${plane.model}`); // → 500, cannot happen for seeded data
|
||||||
const distanceKm = haversineKm(origin.lat, origin.lon, destFeature.properties.lat, destFeature.properties.lon);
|
const distanceKm = haversineKm(origin.lat, origin.lon, destFeature.properties.lat, destFeature.properties.lon);
|
||||||
const burnL = type.burnPerKm * distanceKm;
|
// Weighted burn model (v0.16.0): the leg needs enough fuel to cover it arriving empty.
|
||||||
if (burnL > plane.fuel) {
|
const requiredL = requiredFuelFor(type.burnPerKm, type.emptyWeightKg, type.maxFuel, distanceKm);
|
||||||
throw new GameActionError(409, `insufficient fuel: the leg needs ${Math.round(burnL)} L but the plane has ${Math.round(plane.fuel)} L`);
|
if (requiredL > plane.fuel) {
|
||||||
|
throw new GameActionError(409, `insufficient fuel: the leg needs ${Math.round(requiredL)} L but the plane has ${Math.round(plane.fuel)} L`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// runAction() ticked first, so this is current game time.
|
// runAction() ticked first, so this is current game time.
|
||||||
@@ -123,6 +125,56 @@ export async function flyPlane(inst: GameDb, planeId: string, destIcao: string):
|
|||||||
lon: origin.lon,
|
lon: origin.lon,
|
||||||
})
|
})
|
||||||
.where(eq(schema.planes.id, planeId));
|
.where(eq(schema.planes.id, planeId));
|
||||||
|
// ISS-057: dispatch still resumes a MANUALLY paused sim (pause is manual-only now — landings
|
||||||
|
// slow to 1× instead of pausing), and restores the last manually selected speed when this
|
||||||
|
// dispatch took the LAST grounded plane airborne. Runs inside runAction(), so tick + controls
|
||||||
|
// + dispatch are atomic under the sim lock.
|
||||||
|
const sets: Partial<Pick<schema.SimStateRow, 'paused' | 'timeScale'>> = { paused: false };
|
||||||
|
const remaining = await inst.db.select().from(schema.planes).where(eq(schema.planes.status, 'available'));
|
||||||
|
if (remaining.length === 0) sets.timeScale = sim.lastSelectedTimeScale;
|
||||||
|
await inst.db.update(schema.simState).set(sets);
|
||||||
|
await persist(inst);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Queue (POST /api/planes/:id/queue {destIcao}) — ISS-043 part 1 ---
|
||||||
|
|
||||||
|
// Append a NOT-yet-started leg to the plane's queue. Works whether the plane is
|
||||||
|
// grounded or flying (you can pre-build a route); nothing auto-starts here — the
|
||||||
|
// active leg still starts via flyPlane, and queued legs chain on landing when fuel
|
||||||
|
// covers them (lib/sim/engine.ts deliverPackages). Validation: known plane, ICAO
|
||||||
|
// in the airport dataset.
|
||||||
|
export async function queueLeg(inst: GameDb, planeId: string, destIcao: string): Promise<void> {
|
||||||
|
const planeRows = await inst.db.select().from(schema.planes).where(eq(schema.planes.id, planeId));
|
||||||
|
const plane = planeRows[0];
|
||||||
|
if (!plane) throw new GameActionError(404, `plane ${planeId} not found`);
|
||||||
|
|
||||||
|
const fc = await loadAirportsGeoJson();
|
||||||
|
if (!fc.features.some((f) => f.properties.icao === destIcao)) {
|
||||||
|
throw new GameActionError(400, `unknown airport ${destIcao}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const queue = parseIcaoQueue(plane.queue);
|
||||||
|
queue.push(destIcao);
|
||||||
|
await inst.db.update(schema.planes).set({ queue: JSON.stringify(queue) }).where(eq(schema.planes.id, planeId));
|
||||||
|
await persist(inst);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Queue cancel (POST /api/planes/:id/queue/cancel {index}) — ISS-043 part 1 ---
|
||||||
|
|
||||||
|
// Remove a NOT-yet-started leg from the queue by index. Only queued legs are
|
||||||
|
// cancellable — the active in-flight leg (destIcao) is never affected. Validation:
|
||||||
|
// known plane, integer index within [0, queue.length).
|
||||||
|
export async function cancelQueuedLeg(inst: GameDb, planeId: string, index: number): Promise<void> {
|
||||||
|
const planeRows = await inst.db.select().from(schema.planes).where(eq(schema.planes.id, planeId));
|
||||||
|
const plane = planeRows[0];
|
||||||
|
if (!plane) throw new GameActionError(404, `plane ${planeId} not found`);
|
||||||
|
|
||||||
|
const queue = parseIcaoQueue(plane.queue);
|
||||||
|
if (index < 0 || index >= queue.length) {
|
||||||
|
throw new GameActionError(400, `queue index ${index} out of range — the queue holds ${queue.length} legs`);
|
||||||
|
}
|
||||||
|
queue.splice(index, 1);
|
||||||
|
await inst.db.update(schema.planes).set({ queue: JSON.stringify(queue) }).where(eq(schema.planes.id, planeId));
|
||||||
await persist(inst);
|
await persist(inst);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -160,6 +212,23 @@ export async function abandonPackage(inst: GameDb, packageId: string): Promise<{
|
|||||||
return { penalty };
|
return { penalty };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Ignore (POST /api/packages/:id/ignore) — ISS-047 part B ---
|
||||||
|
|
||||||
|
// Dismiss an OPEN job so it leaves the market permanently; no penalty, nothing else
|
||||||
|
// changes. The top-up logic (spawnOpenPackages counts 'open') refills the market with
|
||||||
|
// a new random package on the next tick. 404 unknown id; 409 unless open.
|
||||||
|
export async function ignorePackage(inst: GameDb, packageId: string): Promise<void> {
|
||||||
|
const pkgRows = await inst.db.select().from(schema.packages).where(eq(schema.packages.id, packageId));
|
||||||
|
const pkg = pkgRows[0];
|
||||||
|
if (!pkg) throw new GameActionError(404, `package ${packageId} not found`);
|
||||||
|
if (pkg.status !== 'open') {
|
||||||
|
throw new GameActionError(409, `package is ${pkg.status}, only open packages can be ignored`);
|
||||||
|
}
|
||||||
|
|
||||||
|
await inst.db.update(schema.packages).set({ status: 'ignored' }).where(eq(schema.packages.id, packageId));
|
||||||
|
await persist(inst);
|
||||||
|
}
|
||||||
|
|
||||||
// --- Market (POST /api/market/buy-plane {model}) ---
|
// --- Market (POST /api/market/buy-plane {model}) ---
|
||||||
|
|
||||||
// Buy a catalog model at full price; it arrives 'available' with a full tank at
|
// Buy a catalog model at full price; it arrives 'available' with a full tank at
|
||||||
@@ -208,6 +277,15 @@ export async function sellPlane(inst: GameDb, planeId: string): Promise<{ payout
|
|||||||
throw new GameActionError(409, `plane is ${plane.status}, only grounded planes can be sold`);
|
throw new GameActionError(409, `plane is ${plane.status}, only grounded planes can be sold`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// v0.28.0: selling a plane that still carries cargo would orphan it — the packages stay
|
||||||
|
// 'loaded'/'expired' with a dangling planeId and could never deliver (same query pattern as loadPackage).
|
||||||
|
const carrying = await inst.db.select({ id: schema.packages.id }).from(schema.packages).where(
|
||||||
|
and(inArray(schema.packages.status, ['loaded', 'expired']), eq(schema.packages.planeId, plane.id)),
|
||||||
|
);
|
||||||
|
if (carrying.length > 0) {
|
||||||
|
throw new GameActionError(409, `cannot sell a plane carrying cargo`);
|
||||||
|
}
|
||||||
|
|
||||||
const all = await inst.db.select().from(schema.planes);
|
const all = await inst.db.select().from(schema.planes);
|
||||||
if (all.length <= 1) throw new GameActionError(409, 'cannot sell the last remaining plane');
|
if (all.length <= 1) throw new GameActionError(409, 'cannot sell the last remaining plane');
|
||||||
|
|
||||||
@@ -225,8 +303,19 @@ export async function sellPlane(inst: GameDb, planeId: string): Promise<{ payout
|
|||||||
|
|
||||||
// --- Refuel (POST /api/planes/:planeId/refuel) ---
|
// --- Refuel (POST /api/planes/:planeId/refuel) ---
|
||||||
|
|
||||||
// Fill a grounded plane to maxFuel at FUEL_PRICE_PER_L per missing liter.
|
// Refuel modes (v0.16.0): 'full' fills the tank to maxFuel; 'forFlight' adds just
|
||||||
export async function refuelPlane(inst: GameDb, planeId: string): Promise<{ cost: number }> {
|
// enough fuel for one loaded package's destination leg — required liters per the
|
||||||
|
// weighted burn model, independent of how much is already in the tank.
|
||||||
|
export interface RefuelOptions {
|
||||||
|
mode?: 'full' | 'forFlight';
|
||||||
|
packageId?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fill a grounded plane to maxFuel at FUEL_PRICE_PER_L per missing liter — or, with
|
||||||
|
// {mode:'forFlight', packageId}, top it up just enough to fly the loaded package's
|
||||||
|
// destination leg (409 if the package isn't loaded on this plane, is expired, or the
|
||||||
|
// leg doesn't fit a full tank).
|
||||||
|
export async function refuelPlane(inst: GameDb, planeId: string, opts: RefuelOptions = {}): Promise<{ cost: number }> {
|
||||||
const rows = await inst.db.select().from(schema.planes).where(eq(schema.planes.id, planeId));
|
const rows = await inst.db.select().from(schema.planes).where(eq(schema.planes.id, planeId));
|
||||||
const plane = rows[0];
|
const plane = rows[0];
|
||||||
if (!plane) throw new GameActionError(404, `plane ${planeId} not found`);
|
if (!plane) throw new GameActionError(404, `plane ${planeId} not found`);
|
||||||
@@ -234,14 +323,47 @@ export async function refuelPlane(inst: GameDb, planeId: string): Promise<{ cost
|
|||||||
throw new GameActionError(409, `plane is ${plane.status}, only grounded planes can be refueled`);
|
throw new GameActionError(409, `plane is ${plane.status}, only grounded planes can be refueled`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const cost = Math.round((plane.maxFuel - plane.fuel) * FUEL_PRICE_PER_L * 100) / 100;
|
const mode = opts.mode ?? 'full';
|
||||||
|
let targetFuel: number; // tank level after the refuel
|
||||||
|
if (mode === 'forFlight') {
|
||||||
|
if (!opts.packageId) throw new GameActionError(400, 'packageId is required when mode is "forFlight"');
|
||||||
|
|
||||||
|
const pkgRows = await inst.db.select().from(schema.packages).where(eq(schema.packages.id, opts.packageId));
|
||||||
|
const pkg = pkgRows[0];
|
||||||
|
if (!pkg) throw new GameActionError(404, `package ${opts.packageId} not found`);
|
||||||
|
if (pkg.status !== 'loaded' || pkg.planeId !== plane.id) {
|
||||||
|
const where = pkg.planeId === plane.id ? '' : ', and it is bound to another plane';
|
||||||
|
throw new GameActionError(409, `only a package loaded on this plane can be refueled for (it is ${pkg.status}${where})`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const type = PLANE_TYPES[plane.model];
|
||||||
|
if (!type) throw new Error(`unknown plane model ${plane.model}`); // → 500, cannot happen for seeded data
|
||||||
|
const origin = await airportByIcao(plane.locationIcao);
|
||||||
|
const dest = await airportByIcao(pkg.destIcao);
|
||||||
|
const distanceKm = haversineKm(origin.lat, origin.lon, dest.lat, dest.lon);
|
||||||
|
const requiredL = requiredFuelFor(type.burnPerKm, type.emptyWeightKg, type.maxFuel, distanceKm);
|
||||||
|
if (requiredL > plane.maxFuel) {
|
||||||
|
throw new GameActionError(409, `the leg to ${pkg.destIcao} needs ${Math.round(requiredL)} L even starting empty — it does not fit a full ${plane.maxFuel} L tank`);
|
||||||
|
}
|
||||||
|
// Land EXACTLY on the leg requirement when topping up: flyPlane re-computes this same value and
|
||||||
|
// compares with strict `>`, so fuel := requiredL guarantees the leg is feasible. The alternative
|
||||||
|
// (fuel + liters) can round a hair BELOW R in IEEE754 — f + fl(R − f) is not guaranteed ≥ R — and
|
||||||
|
// would 409 on an otherwise-feasible leg. Already enough → free no-op, tank untouched.
|
||||||
|
targetFuel = Math.max(plane.fuel, requiredL);
|
||||||
|
} else {
|
||||||
|
// Exactly maxFuel (as before v0.16.0) — clients/tests compare against it with strict equality.
|
||||||
|
targetFuel = plane.maxFuel;
|
||||||
|
}
|
||||||
|
|
||||||
|
const liters = Math.max(0, targetFuel - plane.fuel);
|
||||||
|
const cost = Math.round(liters * FUEL_PRICE_PER_L * 100) / 100;
|
||||||
const account = (await inst.db.select().from(schema.account))[0];
|
const account = (await inst.db.select().from(schema.account))[0];
|
||||||
if (!account) throw new Error('account row missing');
|
if (!account) throw new Error('account row missing');
|
||||||
if (cost > 0 && account.cash < cost) {
|
if (cost > 0 && account.cash < cost) {
|
||||||
throw new GameActionError(409, `insufficient funds: refueling costs ${cost}, you have ${Math.round(account.cash)}`);
|
throw new GameActionError(409, `insufficient funds: refueling costs ${cost}, you have ${Math.round(account.cash)}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
await inst.db.update(schema.planes).set({ fuel: plane.maxFuel }).where(eq(schema.planes.id, planeId));
|
await inst.db.update(schema.planes).set({ fuel: targetFuel }).where(eq(schema.planes.id, planeId));
|
||||||
if (cost > 0) {
|
if (cost > 0) {
|
||||||
await inst.db.update(schema.account).set({ cash: Math.round((account.cash - cost) * 100) / 100 });
|
await inst.db.update(schema.account).set({ cash: Math.round((account.cash - cost) * 100) / 100 });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { PLANE_TYPES, STARTER_MODEL } from './catalog';
|
||||||
|
|
||||||
|
// v0.28.0 (ISS-047) — catalog sanity: the progression ladder must stay well-formed as types are added.
|
||||||
|
describe('PLANE_TYPES', () => {
|
||||||
|
it('every entry has positive specs and a unique id', () => {
|
||||||
|
const ids = Object.keys(PLANE_TYPES);
|
||||||
|
expect(new Set(ids).size).toBe(ids.length);
|
||||||
|
for (const t of Object.values(PLANE_TYPES)) {
|
||||||
|
expect(t.id, `${t.name} id`).toBeTruthy();
|
||||||
|
expect(t.price, `${t.name} price`).toBeGreaterThan(0);
|
||||||
|
expect(t.maxFuel, `${t.name} maxFuel`).toBeGreaterThan(0);
|
||||||
|
expect(t.burnPerKm, `${t.name} burnPerKm`).toBeGreaterThan(0);
|
||||||
|
expect(t.emptyWeightKg, `${t.name} emptyWeightKg`).toBeGreaterThan(0);
|
||||||
|
expect(t.speedKmh, `${t.name} speedKmh`).toBeGreaterThan(0);
|
||||||
|
expect(t.maxPayloadKg, `${t.name} maxPayloadKg`).toBeGreaterThan(0);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('atr72 is the starter model', () => {
|
||||||
|
expect(STARTER_MODEL).toBe('atr72');
|
||||||
|
expect(PLANE_TYPES[STARTER_MODEL]).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
+74
-7
@@ -6,15 +6,20 @@ export interface PlaneType {
|
|||||||
name: string;
|
name: string;
|
||||||
// Fuel capacity, liters.
|
// Fuel capacity, liters.
|
||||||
maxFuel: number;
|
maxFuel: number;
|
||||||
// Fuel burn per km of flight, liters/km (cruise).
|
// Fuel burn per km of flight at a FULL tank, liters/km (cruise) — the weighted burn
|
||||||
|
// model (v0.16.0) calibrates its rate constant to this value at F = maxFuel.
|
||||||
burnPerKm: number;
|
burnPerKm: number;
|
||||||
|
// Operating empty weight in kg (v0.16.0) — feeds the weight-proportional burn model.
|
||||||
|
emptyWeightKg: number;
|
||||||
// Cruise speed, km/h — used by the sim tick to advance planes along routes.
|
// Cruise speed, km/h — used by the sim tick to advance planes along routes.
|
||||||
speedKmh: number;
|
speedKmh: number;
|
||||||
// Market price in € (v0.8.0): buying costs `price`, selling pays out
|
// Market price in € (v0.8.0): buying costs `price`, selling pays out
|
||||||
// SELL_FRACTION × price.
|
// SELL_FRACTION × price.
|
||||||
price: number;
|
price: number;
|
||||||
// Cargo slot capacity (v0.12.0): how many packages can be loaded on one plane.
|
// Max payload in kg (v0.27.0, ISS-045 — replaces the v0.12.0 slot count): total
|
||||||
capacity: number;
|
// package weight that can be loaded on one plane. ATR 72-600-class figure, tuned
|
||||||
|
// so every cargo type at max count × 1.3 jitter still fits alone (see UNIT_WEIGHT_KG).
|
||||||
|
maxPayloadKg: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const PLANE_TYPES: Record<string, PlaneType> = {
|
export const PLANE_TYPES: Record<string, PlaneType> = {
|
||||||
@@ -22,12 +27,69 @@ export const PLANE_TYPES: Record<string, PlaneType> = {
|
|||||||
id: 'atr72',
|
id: 'atr72',
|
||||||
name: 'ATR 72-600',
|
name: 'ATR 72-600',
|
||||||
maxFuel: 6300,
|
maxFuel: 6300,
|
||||||
burnPerKm: 1.75, // ~900 kg/h at 510 km/h cruise (Jet-A1 ≈ 0.8 kg/L)
|
burnPerKm: 1.75, // full-tank rate: ~893 L/h ≈ 714 kg/h at 510 km/h cruise (Jet-A1 ≈ 0.8 kg/L); the weighted model burns less as fuel drops off
|
||||||
|
emptyWeightKg: 9_300, // ATR 72-600 operating empty weight
|
||||||
speedKmh: 510,
|
speedKmh: 510,
|
||||||
// €200k — with the starting cash of €20k and typical hop rewards (~€1–3k),
|
// €200k — with the starting cash of €20k and typical hop rewards (~€1–3k),
|
||||||
// a second ATR takes sustained play to afford, as intended for the MVP sink.
|
// a second ATR takes sustained play to afford, as intended for the MVP sink.
|
||||||
price: 200_000,
|
price: 200_000,
|
||||||
capacity: 6,
|
// ponytail: balance-tunable payload (kg) — every cargo type at max count × 1.3 jitter
|
||||||
|
// must stay below this so any single package fits alone; typical loads carry ~3–6 packages.
|
||||||
|
maxPayloadKg: 4_800,
|
||||||
|
},
|
||||||
|
// Progression ladder above the ATR starter (v0.28.0, ISS-047): bigger tanks, faster airframes,
|
||||||
|
// higher prices — everything downstream is data-driven via PLANE_TYPES[model]. Values are
|
||||||
|
// balance-tunable; keep maxPayloadKg ≥ every cargo type at max count × 1.3 jitter so any
|
||||||
|
// single package still fits alone (same rule as the ATR above).
|
||||||
|
crj900: {
|
||||||
|
id: 'crj900',
|
||||||
|
name: 'CRJ-900',
|
||||||
|
maxFuel: 8_000,
|
||||||
|
burnPerKm: 2.1,
|
||||||
|
emptyWeightKg: 17_500,
|
||||||
|
speedKmh: 830,
|
||||||
|
price: 450_000,
|
||||||
|
maxPayloadKg: 6_500,
|
||||||
|
},
|
||||||
|
e175: {
|
||||||
|
id: 'e175',
|
||||||
|
name: 'Embraer E175',
|
||||||
|
maxFuel: 9_500,
|
||||||
|
burnPerKm: 2.0,
|
||||||
|
emptyWeightKg: 23_000,
|
||||||
|
speedKmh: 840,
|
||||||
|
price: 900_000,
|
||||||
|
maxPayloadKg: 9_000,
|
||||||
|
},
|
||||||
|
a320: {
|
||||||
|
id: 'a320',
|
||||||
|
name: 'Airbus A320-200',
|
||||||
|
maxFuel: 12_000,
|
||||||
|
burnPerKm: 2.2,
|
||||||
|
emptyWeightKg: 41_000,
|
||||||
|
speedKmh: 845,
|
||||||
|
price: 1_800_000,
|
||||||
|
maxPayloadKg: 18_000,
|
||||||
|
},
|
||||||
|
a330: {
|
||||||
|
id: 'a330',
|
||||||
|
name: 'Airbus A330-200',
|
||||||
|
maxFuel: 20_000,
|
||||||
|
burnPerKm: 2.16,
|
||||||
|
emptyWeightKg: 95_000,
|
||||||
|
speedKmh: 910,
|
||||||
|
price: 4_500_000,
|
||||||
|
maxPayloadKg: 48_000,
|
||||||
|
},
|
||||||
|
b777: {
|
||||||
|
id: 'b777',
|
||||||
|
name: 'Boeing 777-300ER',
|
||||||
|
maxFuel: 30_000,
|
||||||
|
burnPerKm: 2.5,
|
||||||
|
emptyWeightKg: 130_000,
|
||||||
|
speedKmh: 920,
|
||||||
|
price: 9_000_000,
|
||||||
|
maxPayloadKg: 80_000,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -49,8 +111,12 @@ export interface CatalogEntry {
|
|||||||
price: number;
|
price: number;
|
||||||
maxFuel: number;
|
maxFuel: number;
|
||||||
burnPerKm: number;
|
burnPerKm: number;
|
||||||
|
// Weighted burn model inputs (v0.16.0) — clients can mirror the closed forms in
|
||||||
|
// lib/sim/movement.ts with these + FUEL_DENSITY_KG_PER_L.
|
||||||
|
emptyWeightKg: number;
|
||||||
speedKmh: number;
|
speedKmh: number;
|
||||||
capacity: number;
|
// Max payload in kg (v0.27.0) — total package weight that can be loaded on one plane.
|
||||||
|
maxPayloadKg: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The catalog as a flat array, one entry per plane type — the single source of
|
// The catalog as a flat array, one entry per plane type — the single source of
|
||||||
@@ -62,7 +128,8 @@ export function catalogEntries(): CatalogEntry[] {
|
|||||||
price: t.price,
|
price: t.price,
|
||||||
maxFuel: t.maxFuel,
|
maxFuel: t.maxFuel,
|
||||||
burnPerKm: t.burnPerKm,
|
burnPerKm: t.burnPerKm,
|
||||||
|
emptyWeightKg: t.emptyWeightKg,
|
||||||
speedKmh: t.speedKmh,
|
speedKmh: t.speedKmh,
|
||||||
capacity: t.capacity,
|
maxPayloadKg: t.maxPayloadKg,
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|||||||
+52
-11
@@ -9,8 +9,9 @@ import {
|
|||||||
generatePackage,
|
generatePackage,
|
||||||
HUB_ICAO,
|
HUB_ICAO,
|
||||||
mulberry32,
|
mulberry32,
|
||||||
|
REWARD_PER_KG,
|
||||||
REWARD_PER_KM,
|
REWARD_PER_KM,
|
||||||
rewardForDistanceKm,
|
rewardFor,
|
||||||
STARTING_CASH,
|
STARTING_CASH,
|
||||||
STARTING_REPUTATION,
|
STARTING_REPUTATION,
|
||||||
type SeedAirport,
|
type SeedAirport,
|
||||||
@@ -44,6 +45,7 @@ describe('buildSeed', () => {
|
|||||||
destIcao: null,
|
destIcao: null,
|
||||||
lat: 50.0333,
|
lat: 50.0333,
|
||||||
lon: 8.5706,
|
lon: 8.5706,
|
||||||
|
queue: [], // v0.25.0 (ISS-043) — no queued legs on first run
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -69,12 +71,26 @@ describe('buildSeed', () => {
|
|||||||
expect(new Set(seed.packages.map((c) => c.id)).size).toBe(seed.packages.length);
|
expect(new Set(seed.packages.map((c) => c.id)).size).toBe(seed.packages.length);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('scales reward by haversine distance: round(500 + 2.5 * km)', () => {
|
it('applies the reward formula: round(500 + 2.5 * km + 0.5 * weightKg)', () => {
|
||||||
const seed = seedWith(42);
|
const seed = seedWith(42);
|
||||||
for (const c of seed.packages) {
|
for (const c of seed.packages) {
|
||||||
const o = AIRPORTS.find((a) => a.icao === c.originIcao)!;
|
const o = AIRPORTS.find((a) => a.icao === c.originIcao)!;
|
||||||
const d = AIRPORTS.find((a) => a.icao === c.destIcao)!;
|
const d = AIRPORTS.find((a) => a.icao === c.destIcao)!;
|
||||||
expect(c.reward).toBe(Math.round(BASE_REWARD + REWARD_PER_KM * haversineKm(o.lat, o.lon, d.lat, d.lon)));
|
expect(c.reward).toBe(
|
||||||
|
Math.round(BASE_REWARD + REWARD_PER_KM * haversineKm(o.lat, o.lon, d.lat, d.lon) + REWARD_PER_KG * c.weightKg),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('gives every package a positive integer weight that fits the starter plane alone (balance constraint)', () => {
|
||||||
|
const maxPayload = PLANE_TYPES[STARTER_MODEL].maxPayloadKg;
|
||||||
|
for (const seed of [seedWith(42), seedWith(7)]) {
|
||||||
|
for (const c of seed.packages) {
|
||||||
|
expect(Number.isInteger(c.weightKg)).toBe(true);
|
||||||
|
expect(c.weightKg).toBeGreaterThan(0);
|
||||||
|
// max count × max jitter (1.3×) must still fit the ATR alone — see UNIT_WEIGHT_KG.
|
||||||
|
expect(c.weightKg).toBeLessThanOrEqual(maxPayload);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -89,8 +105,9 @@ describe('buildSeed', () => {
|
|||||||
it('seeds the starting account and sim state', () => {
|
it('seeds the starting account and sim state', () => {
|
||||||
const seed = seedWith(42);
|
const seed = seedWith(42);
|
||||||
expect(seed.account).toEqual({ cash: STARTING_CASH, reputation: STARTING_REPUTATION });
|
expect(seed.account).toEqual({ cash: STARTING_CASH, reputation: STARTING_REPUTATION });
|
||||||
// lastRealTickMs starts at the seed moment so the first tick-on-read advances ~0.
|
// lastRealTickMs starts at the seed moment so the first tick-on-read advances ~0;
|
||||||
expect(seed.simState).toEqual({ clockMs: NOW, timeScale: 1, paused: false, lastRealTickMs: NOW });
|
// lastSelectedTimeScale mirrors the seeded speed (v0.30.0, ISS-057).
|
||||||
|
expect(seed.simState).toEqual({ clockMs: NOW, timeScale: 1, paused: false, lastRealTickMs: NOW, lastSelectedTimeScale: 1 });
|
||||||
});
|
});
|
||||||
|
|
||||||
it('is fully deterministic for a fixed RNG and inputs', () => {
|
it('is fully deterministic for a fixed RNG and inputs', () => {
|
||||||
@@ -105,9 +122,9 @@ describe('buildSeed', () => {
|
|||||||
expect(() => buildSeed({ airports: AIRPORTS.slice(0, 1), rng: mulberry32(42), nowMs: NOW })).toThrow();
|
expect(() => buildSeed({ airports: AIRPORTS.slice(0, 1), rng: mulberry32(42), nowMs: NOW })).toThrow();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('rewardForDistanceKm applies the documented formula', () => {
|
it('rewardFor applies the documented formula', () => {
|
||||||
expect(rewardForDistanceKm(0)).toBe(BASE_REWARD);
|
expect(rewardFor(0, 0)).toBe(BASE_REWARD);
|
||||||
expect(rewardForDistanceKm(1000)).toBe(Math.round(BASE_REWARD + REWARD_PER_KM * 1000));
|
expect(rewardFor(1000, 2_000)).toBe(Math.round(BASE_REWARD + REWARD_PER_KM * 1000 + REWARD_PER_KG * 2_000));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -126,7 +143,9 @@ describe('generatePackage (shared seed/spawn builder)', () => {
|
|||||||
|
|
||||||
const o = AIRPORTS.find((a) => a.icao === c.originIcao)!;
|
const o = AIRPORTS.find((a) => a.icao === c.originIcao)!;
|
||||||
const d = AIRPORTS.find((a) => a.icao === c.destIcao)!;
|
const d = AIRPORTS.find((a) => a.icao === c.destIcao)!;
|
||||||
expect(c.reward).toBe(Math.round(BASE_REWARD + REWARD_PER_KM * haversineKm(o.lat, o.lon, d.lat, d.lon)));
|
expect(c.reward).toBe(
|
||||||
|
Math.round(BASE_REWARD + REWARD_PER_KM * haversineKm(o.lat, o.lon, d.lat, d.lon) + REWARD_PER_KG * c.weightKg),
|
||||||
|
);
|
||||||
|
|
||||||
// Same 6–72h game-time deadline window as the seed.
|
// Same 6–72h game-time deadline window as the seed.
|
||||||
expect(c.deadlineSimTime).toBeGreaterThan(NOW + 6 * 3_600_000 - 1);
|
expect(c.deadlineSimTime).toBeGreaterThan(NOW + 6 * 3_600_000 - 1);
|
||||||
@@ -172,7 +191,9 @@ describe('generatePackage (shared seed/spawn builder)', () => {
|
|||||||
|
|
||||||
const o = AIRPORTS.find((a) => a.icao === c.originIcao)!;
|
const o = AIRPORTS.find((a) => a.icao === c.originIcao)!;
|
||||||
const d = AIRPORTS.find((a) => a.icao === c.destIcao)!;
|
const d = AIRPORTS.find((a) => a.icao === c.destIcao)!;
|
||||||
expect(c.reward).toBe(Math.round(BASE_REWARD + REWARD_PER_KM * haversineKm(o.lat, o.lon, d.lat, d.lon)));
|
expect(c.reward).toBe(
|
||||||
|
Math.round(BASE_REWARD + REWARD_PER_KM * haversineKm(o.lat, o.lon, d.lat, d.lon) + REWARD_PER_KG * c.weightKg),
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('destIcao forces the destination; origin stays random but distinct', () => {
|
it('destIcao forces the destination; origin stays random but distinct', () => {
|
||||||
@@ -188,7 +209,9 @@ describe('generatePackage (shared seed/spawn builder)', () => {
|
|||||||
|
|
||||||
const o = AIRPORTS[0]; // EDDF
|
const o = AIRPORTS[0]; // EDDF
|
||||||
const d = AIRPORTS[1]; // EHAM
|
const d = AIRPORTS[1]; // EHAM
|
||||||
expect(c.reward).toBe(Math.round(BASE_REWARD + REWARD_PER_KM * haversineKm(o.lat, o.lon, d.lat, d.lon)));
|
expect(c.reward).toBe(
|
||||||
|
Math.round(BASE_REWARD + REWARD_PER_KM * haversineKm(o.lat, o.lon, d.lat, d.lon) + REWARD_PER_KG * c.weightKg),
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('is deterministic for a fixed RNG with forced endpoints', () => {
|
it('is deterministic for a fixed RNG with forced endpoints', () => {
|
||||||
@@ -211,4 +234,22 @@ describe('generatePackage (shared seed/spawn builder)', () => {
|
|||||||
expect(a).toEqual(b);
|
expect(a).toEqual(b);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('forced weight (v0.27.0 e2e hook)', () => {
|
||||||
|
it('weightKg forces the package weight and feeds the payout', () => {
|
||||||
|
const c = generatePackage({ id: 'c-w', airports: AIRPORTS, rng: mulberry32(42), nowMs: NOW, weightKg: 1_234 });
|
||||||
|
expect(c.weightKg).toBe(1_234);
|
||||||
|
|
||||||
|
const o = AIRPORTS.find((a) => a.icao === c.originIcao)!;
|
||||||
|
const d = AIRPORTS.find((a) => a.icao === c.destIcao)!;
|
||||||
|
expect(c.reward).toBe(Math.round(BASE_REWARD + REWARD_PER_KM * haversineKm(o.lat, o.lon, d.lat, d.lon) + REWARD_PER_KG * 1_234));
|
||||||
|
|
||||||
|
// Deterministic for a fixed RNG…
|
||||||
|
const again = generatePackage({ id: 'c-w', airports: AIRPORTS, rng: mulberry32(42), nowMs: NOW, weightKg: 1_234 });
|
||||||
|
expect(again).toEqual(c);
|
||||||
|
// …and the forced value consumes no RNG draw — the deadline lands where an unforced call's jitter would.
|
||||||
|
const unforced = generatePackage({ id: 'c-u', airports: AIRPORTS, rng: mulberry32(42), nowMs: NOW });
|
||||||
|
expect(c.deadlineSimTime).not.toBe(unforced.deadlineSimTime);
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+40
-11
@@ -38,6 +38,9 @@ export interface SeedPlane {
|
|||||||
destIcao: null;
|
destIcao: null;
|
||||||
lat: number;
|
lat: number;
|
||||||
lon: number;
|
lon: number;
|
||||||
|
// Upcoming legs not yet started (v0.25.0, ISS-043) — serialized to the queue
|
||||||
|
// column as JSON text on insert; defaults to an empty queue.
|
||||||
|
queue?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SeedPackage {
|
export interface SeedPackage {
|
||||||
@@ -47,6 +50,8 @@ export interface SeedPackage {
|
|||||||
reward: number;
|
reward: number;
|
||||||
cargoType: string;
|
cargoType: string;
|
||||||
cargoCount: number;
|
cargoCount: number;
|
||||||
|
// Package weight in kg (v0.27.0, ISS-045) — unit weight × count with ±30% jitter.
|
||||||
|
weightKg: number;
|
||||||
deadlineSimTime: number;
|
deadlineSimTime: number;
|
||||||
status: 'open';
|
status: 'open';
|
||||||
planeId: null;
|
planeId: null;
|
||||||
@@ -57,7 +62,7 @@ export interface SeedData {
|
|||||||
plane: SeedPlane;
|
plane: SeedPlane;
|
||||||
packages: SeedPackage[];
|
packages: SeedPackage[];
|
||||||
account: { cash: number; reputation: number };
|
account: { cash: number; reputation: number };
|
||||||
simState: { clockMs: number; timeScale: number; paused: false; lastRealTickMs: number };
|
simState: { clockMs: number; timeScale: number; paused: false; lastRealTickMs: number; lastSelectedTimeScale: number };
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Tunables (documented so future revenue/cost work can build on them) ---
|
// --- Tunables (documented so future revenue/cost work can build on them) ---
|
||||||
@@ -77,10 +82,12 @@ export const PACKAGE_COUNT_MAX = 12; // inclusive
|
|||||||
// count after expiries, so the job board never runs dry.
|
// count after expiries, so the job board never runs dry.
|
||||||
export const MARKET_TARGET_OPEN_PACKAGES = 10;
|
export const MARKET_TARGET_OPEN_PACKAGES = 10;
|
||||||
|
|
||||||
// Reward formula (v0.6.0 — deliberately simple; real revenue/cost modeling is a
|
// Reward formula (v0.6.0 distance part, deliberately simple; real revenue/cost
|
||||||
// later increment): reward = BASE_REWARD + REWARD_PER_KM * great-circle km.
|
// modeling is a later increment; v0.27.0 weight part): reward = BASE_REWARD +
|
||||||
|
// REWARD_PER_KM * great-circle km + REWARD_PER_KG * package weight kg.
|
||||||
export const BASE_REWARD = 500;
|
export const BASE_REWARD = 500;
|
||||||
export const REWARD_PER_KM = 2.5;
|
export const REWARD_PER_KM = 2.5;
|
||||||
|
export const REWARD_PER_KG = 0.5;
|
||||||
|
|
||||||
// Package deadlines: now + a plausible game-time window of 6–72 hours.
|
// Package deadlines: now + a plausible game-time window of 6–72 hours.
|
||||||
const DEADLINE_MIN_HOURS = 6;
|
const DEADLINE_MIN_HOURS = 6;
|
||||||
@@ -88,19 +95,33 @@ const DEADLINE_MAX_HOURS = 72;
|
|||||||
|
|
||||||
const CARGO_TYPES = ['Passengers', 'Mail', 'Perishables', 'Electronics', 'Auto parts'] as const;
|
const CARGO_TYPES = ['Passengers', 'Mail', 'Perishables', 'Electronics', 'Auto parts'] as const;
|
||||||
|
|
||||||
export function rewardForDistanceKm(km: number): number {
|
// ponytail: balance-tunable unit weights (kg per passenger/pallet). Chosen so every cargo
|
||||||
return Math.round(BASE_REWARD + REWARD_PER_KM * km);
|
// type at MAX count × max jitter (1.3×) still fits the ATR 72-600's payload alone, and
|
||||||
|
// typical packages land ~400–2500 kg — a normal flight carries roughly 3–6 by weight.
|
||||||
|
export const UNIT_WEIGHT_KG: Record<string, number> = {
|
||||||
|
Passengers: 50, // max 50 × 68 × 1.3 = 4420 < 4800
|
||||||
|
Mail: 60, // max 60 × 50 × 1.3 = 3900
|
||||||
|
Perishables: 70, // max 70 × 50 × 1.3 = 4550
|
||||||
|
Electronics: 40, // max 40 × 50 × 1.3 = 2600
|
||||||
|
'Auto parts': 72, // max 72 × 50 × 1.3 = 4680
|
||||||
|
};
|
||||||
|
|
||||||
|
export function rewardFor(km: number, weightKg: number): number {
|
||||||
|
return Math.round(BASE_REWARD + REWARD_PER_KM * km + REWARD_PER_KG * weightKg);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Shared package generator, used by BOTH the first-run seed and the runtime
|
// Shared package generator, used by BOTH the first-run seed and the runtime
|
||||||
// market spawn (v0.7.0) so spawned packages match seeded ones exactly: random
|
// market spawn (v0.7.0) so spawned packages match seeded ones exactly: random
|
||||||
// distinct airports from the dataset, distance-based reward, cargo flavor,
|
// distinct airports from the dataset, distance+weight-based reward, cargo flavor,
|
||||||
// deadline now + 6–72h game time (or now + deadlineOffsetMs when given — used by
|
// weight = unit weight × count with ±30% jitter (v0.27.0), deadline now + 6–72h
|
||||||
// the e2e test hook to force a near-term expiry). The RNG call order per package
|
// game time (or now + deadlineOffsetMs when given — used by the e2e test hook to
|
||||||
// is fixed: origin, dest, cargoType, cargoCount, [deadline window].
|
// force a near-term expiry). The RNG call order per package is fixed: origin,
|
||||||
|
// dest, cargoType, cargoCount, weight jitter, [deadline window].
|
||||||
// v0.8.0: originIcao/destIcao optionally FORCE an endpoint (spawn coverage rule +
|
// v0.8.0: originIcao/destIcao optionally FORCE an endpoint (spawn coverage rule +
|
||||||
// the e2e create-package hook); a forced endpoint consumes no RNG draws, so
|
// the e2e create-package hook); a forced endpoint consumes no RNG draws, so
|
||||||
// callers that omit both get byte-identical behavior to before.
|
// callers that omit both get byte-identical behavior to before.
|
||||||
|
// v0.27.0: weightKg optionally FORCES the package weight (e2e hook) — it skips the
|
||||||
|
// jitter draw, same pattern as forced endpoints.
|
||||||
export function generatePackage(input: {
|
export function generatePackage(input: {
|
||||||
id: string;
|
id: string;
|
||||||
airports: SeedAirport[];
|
airports: SeedAirport[];
|
||||||
@@ -109,6 +130,7 @@ export function generatePackage(input: {
|
|||||||
deadlineOffsetMs?: number;
|
deadlineOffsetMs?: number;
|
||||||
originIcao?: string;
|
originIcao?: string;
|
||||||
destIcao?: string;
|
destIcao?: string;
|
||||||
|
weightKg?: number;
|
||||||
}): SeedPackage {
|
}): SeedPackage {
|
||||||
const { airports, rng, nowMs } = input;
|
const { airports, rng, nowMs } = input;
|
||||||
if (airports.length < 2) throw new Error('package generation needs at least two airports');
|
if (airports.length < 2) throw new Error('package generation needs at least two airports');
|
||||||
@@ -140,6 +162,9 @@ export function generatePackage(input: {
|
|||||||
// Passengers up to the ATR 72's ~68 seats; other cargo in pallets.
|
// Passengers up to the ATR 72's ~68 seats; other cargo in pallets.
|
||||||
const cargoCount =
|
const cargoCount =
|
||||||
cargoType === 'Passengers' ? 1 + Math.floor(rng() * 68) : 1 + Math.floor(rng() * 50);
|
cargoType === 'Passengers' ? 1 + Math.floor(rng() * 68) : 1 + Math.floor(rng() * 50);
|
||||||
|
// Weight (v0.27.0): unit weight × count with ±30% jitter, integer kg — drawn AFTER
|
||||||
|
// cargoCount so the fixed RNG order above holds; a forced weightKg skips the draw.
|
||||||
|
const weightKg = input.weightKg ?? Math.round(UNIT_WEIGHT_KG[cargoType] * cargoCount * (0.7 + 0.6 * rng()));
|
||||||
const deadlineMs =
|
const deadlineMs =
|
||||||
input.deadlineOffsetMs ?? (DEADLINE_MIN_HOURS + rng() * (DEADLINE_MAX_HOURS - DEADLINE_MIN_HOURS)) * 3_600_000;
|
input.deadlineOffsetMs ?? (DEADLINE_MIN_HOURS + rng() * (DEADLINE_MAX_HOURS - DEADLINE_MIN_HOURS)) * 3_600_000;
|
||||||
|
|
||||||
@@ -147,9 +172,10 @@ export function generatePackage(input: {
|
|||||||
id: input.id,
|
id: input.id,
|
||||||
originIcao: origin.icao,
|
originIcao: origin.icao,
|
||||||
destIcao: dest.icao,
|
destIcao: dest.icao,
|
||||||
reward: rewardForDistanceKm(km),
|
reward: rewardFor(km, weightKg),
|
||||||
cargoType,
|
cargoType,
|
||||||
cargoCount,
|
cargoCount,
|
||||||
|
weightKg,
|
||||||
deadlineSimTime: Math.round(nowMs + deadlineMs),
|
deadlineSimTime: Math.round(nowMs + deadlineMs),
|
||||||
status: 'open',
|
status: 'open',
|
||||||
planeId: null,
|
planeId: null,
|
||||||
@@ -182,6 +208,7 @@ export function buildSeed(input: {
|
|||||||
destIcao: null,
|
destIcao: null,
|
||||||
lat: hub.lat,
|
lat: hub.lat,
|
||||||
lon: hub.lon,
|
lon: hub.lon,
|
||||||
|
queue: [], // no queued legs on first run (v0.25.0)
|
||||||
};
|
};
|
||||||
|
|
||||||
const count = PACKAGE_COUNT_MIN + Math.floor(rng() * (PACKAGE_COUNT_MAX - PACKAGE_COUNT_MIN + 1));
|
const count = PACKAGE_COUNT_MIN + Math.floor(rng() * (PACKAGE_COUNT_MAX - PACKAGE_COUNT_MIN + 1));
|
||||||
@@ -198,6 +225,8 @@ export function buildSeed(input: {
|
|||||||
account: { cash: STARTING_CASH, reputation: STARTING_REPUTATION },
|
account: { cash: STARTING_CASH, reputation: STARTING_REPUTATION },
|
||||||
// lastRealTickMs starts at the seed moment so the first tick-on-read advances
|
// lastRealTickMs starts at the seed moment so the first tick-on-read advances
|
||||||
// by ~0 instead of treating "time since install" as elapsed play time.
|
// by ~0 instead of treating "time since install" as elapsed play time.
|
||||||
simState: { clockMs: nowMs, timeScale: 1, paused: false, lastRealTickMs: nowMs },
|
// lastSelectedTimeScale (v0.30.0, ISS-057) mirrors the seeded speed — nothing has been
|
||||||
|
// selected manually yet, so resume would restore 1× anyway.
|
||||||
|
simState: { clockMs: nowMs, timeScale: 1, paused: false, lastRealTickMs: nowMs, lastSelectedTimeScale: 1 },
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
+23
-3
@@ -3,7 +3,7 @@ import { haversineKm } from '@/lib/geo';
|
|||||||
import { getGameDb } from '@/lib/db/client';
|
import { getGameDb } from '@/lib/db/client';
|
||||||
import * as schema from '@/lib/db/schema';
|
import * as schema from '@/lib/db/schema';
|
||||||
import { catalogEntries, FUEL_PRICE_PER_L, PLANE_TYPES, SELL_FRACTION, type CatalogEntry } from './catalog';
|
import { catalogEntries, FUEL_PRICE_PER_L, PLANE_TYPES, SELL_FRACTION, type CatalogEntry } from './catalog';
|
||||||
import { fuelAt, progressAt, positionAt } from '@/lib/sim/movement';
|
import { fuelAtWeighted, progressAt, positionAt } from '@/lib/sim/movement';
|
||||||
|
|
||||||
// Read-only game-state snapshot for client polling (GET /api/state).
|
// Read-only game-state snapshot for client polling (GET /api/state).
|
||||||
|
|
||||||
@@ -24,6 +24,21 @@ export interface PlaneState {
|
|||||||
departureSimTime: number | null;
|
departureSimTime: number | null;
|
||||||
lat: number;
|
lat: number;
|
||||||
lon: number;
|
lon: number;
|
||||||
|
// Upcoming legs NOT yet started (v0.25.0, ISS-043) — ordered ICAOs; the active
|
||||||
|
// leg is destIcao. The engine auto-chains queue[0] on landing when fuel covers it.
|
||||||
|
queue: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse the planes.queue JSON column into an ICAO list (v0.25.0). Guards against
|
||||||
|
// null/empty/malformed values so a corrupt cell can never break a snapshot or tick.
|
||||||
|
export function parseIcaoQueue(raw: string | null): string[] {
|
||||||
|
if (!raw) return [];
|
||||||
|
try {
|
||||||
|
const v: unknown = JSON.parse(raw);
|
||||||
|
return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [];
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PackageState {
|
export interface PackageState {
|
||||||
@@ -35,8 +50,11 @@ export interface PackageState {
|
|||||||
reward: number;
|
reward: number;
|
||||||
cargoType: string;
|
cargoType: string;
|
||||||
cargoCount: number;
|
cargoCount: number;
|
||||||
|
// Package weight in kg (v0.27.0, ISS-045) — drives load validation + per-kg payout.
|
||||||
|
weightKg: number;
|
||||||
deadlineSimTime: number;
|
deadlineSimTime: number;
|
||||||
status: 'open' | 'loaded' | 'delivered' | 'expired' | 'abandoned';
|
// 'ignored' (v0.29.0, ISS-047 part B) = a dismissed open job — terminal, leaves the market.
|
||||||
|
status: 'open' | 'loaded' | 'delivered' | 'expired' | 'abandoned' | 'ignored';
|
||||||
planeId: string | null;
|
planeId: string | null;
|
||||||
createdSimTime: number;
|
createdSimTime: number;
|
||||||
}
|
}
|
||||||
@@ -84,7 +102,7 @@ export async function getStateSnapshot(): Promise<StateSnapshot> {
|
|||||||
const distanceKm = haversineKm(from.lat, from.lon, to.lat, to.lon);
|
const distanceKm = haversineKm(from.lat, from.lon, to.lat, to.lon);
|
||||||
const progress = progressAt(p.departureSimTime, distanceKm, type.speedKmh, simRow.clockMs);
|
const progress = progressAt(p.departureSimTime, distanceKm, type.speedKmh, simRow.clockMs);
|
||||||
const pos = positionAt(from.lat, from.lon, to.lat, to.lon, progress);
|
const pos = positionAt(from.lat, from.lon, to.lat, to.lon, progress);
|
||||||
return { ...pos, fuel: fuelAt(p.fuel, type.burnPerKm, distanceKm, progress) };
|
return { ...pos, fuel: fuelAtWeighted(p.fuel, type.burnPerKm, type.emptyWeightKg, type.maxFuel, distanceKm, progress) };
|
||||||
};
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -108,6 +126,7 @@ export async function getStateSnapshot(): Promise<StateSnapshot> {
|
|||||||
departureSimTime: p.departureSimTime,
|
departureSimTime: p.departureSimTime,
|
||||||
lat: live?.lat ?? p.lat,
|
lat: live?.lat ?? p.lat,
|
||||||
lon: live?.lon ?? p.lon,
|
lon: live?.lon ?? p.lon,
|
||||||
|
queue: parseIcaoQueue(p.queue),
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
packages: packageRows.map((p) => ({
|
packages: packageRows.map((p) => ({
|
||||||
@@ -119,6 +138,7 @@ export async function getStateSnapshot(): Promise<StateSnapshot> {
|
|||||||
reward: p.reward,
|
reward: p.reward,
|
||||||
cargoType: p.cargoType,
|
cargoType: p.cargoType,
|
||||||
cargoCount: p.cargoCount,
|
cargoCount: p.cargoCount,
|
||||||
|
weightKg: p.weightKg,
|
||||||
deadlineSimTime: p.deadlineSimTime,
|
deadlineSimTime: p.deadlineSimTime,
|
||||||
status: p.status,
|
status: p.status,
|
||||||
planeId: p.planeId,
|
planeId: p.planeId,
|
||||||
|
|||||||
+127
-11
@@ -1,6 +1,6 @@
|
|||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import type { StateSnapshot } from './game/state';
|
import type { StateSnapshot } from './game/state';
|
||||||
import { planesGeoJson, routesGeoJson, greatCircleArc, ROUTE_ARC_SEGMENTS, type AirportCoord } from './mapData';
|
import { planesGeoJson, queuedRoutesGeoJson, routesGeoJson, hoverRouteGeoJson, hoverTraceGeoJson, greatCircleArc, ROUTE_ARC_SEGMENTS, type AirportCoord } from './mapData';
|
||||||
import { haversineKm } from './geo';
|
import { haversineKm } from './geo';
|
||||||
|
|
||||||
const AIRPORTS = new Map<string, AirportCoord>([
|
const AIRPORTS = new Map<string, AirportCoord>([
|
||||||
@@ -17,7 +17,7 @@ function snapshot(overrides: Partial<StateSnapshot> = {}): StateSnapshot {
|
|||||||
planes: [],
|
planes: [],
|
||||||
packages: [],
|
packages: [],
|
||||||
catalog: [
|
catalog: [
|
||||||
{ model: 'atr72', label: 'ATR 72-600', price: 200_000, maxFuel: 6300, burnPerKm: 1.75, speedKmh: 510, capacity: 6 },
|
{ model: 'atr72', label: 'ATR 72-600', price: 200_000, maxFuel: 6300, burnPerKm: 1.75, emptyWeightKg: 9_300, speedKmh: 510, maxPayloadKg: 4_800 },
|
||||||
],
|
],
|
||||||
fuelPricePerL: 0.8,
|
fuelPricePerL: 0.8,
|
||||||
sellFraction: 0.5,
|
sellFraction: 0.5,
|
||||||
@@ -34,8 +34,8 @@ describe('planesGeoJson', () => {
|
|||||||
const fc = planesGeoJson(
|
const fc = planesGeoJson(
|
||||||
snapshot({
|
snapshot({
|
||||||
planes: [
|
planes: [
|
||||||
{ id: 'plane-starter', model: 'atr72', status: 'available', fuel: 6300, maxFuel: 6300, locationIcao: 'EDDF', locationName: 'Frankfurt Main Airport', destIcao: null, destName: null, departureSimTime: null, lat: 50.03, lon: 8.56 },
|
{ id: 'plane-starter', model: 'atr72', status: 'available', fuel: 6300, maxFuel: 6300, locationIcao: 'EDDF', locationName: 'Frankfurt Main Airport', destIcao: null, destName: null, departureSimTime: null, lat: 50.03, lon: 8.56, queue: [] },
|
||||||
{ id: 'plane-2', model: 'atr72', status: 'flying', fuel: 4000, maxFuel: 6300, locationIcao: 'EDDF', locationName: 'Frankfurt Main Airport', destIcao: 'EDDV', destName: 'Hannover Airport', departureSimTime: 1000, lat: 51.2, lon: 9.1 },
|
{ id: 'plane-2', model: 'atr72', status: 'flying', fuel: 4000, maxFuel: 6300, locationIcao: 'EDDF', locationName: 'Frankfurt Main Airport', destIcao: 'EDDV', destName: 'Hannover Airport', departureSimTime: 1000, lat: 51.2, lon: 9.1, queue: [] },
|
||||||
],
|
],
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -61,7 +61,7 @@ describe('planesGeoJson', () => {
|
|||||||
snapshot({
|
snapshot({
|
||||||
catalog: [],
|
catalog: [],
|
||||||
planes: [
|
planes: [
|
||||||
{ id: 'p1', model: 'mystery', status: 'available', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'x', destIcao: null, destName: null, departureSimTime: null, lat: 0, lon: 0 },
|
{ id: 'p1', model: 'mystery', status: 'available', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'x', destIcao: null, destName: null, departureSimTime: null, lat: 0, lon: 0, queue: [] },
|
||||||
],
|
],
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -72,7 +72,7 @@ describe('planesGeoJson', () => {
|
|||||||
const fc = planesGeoJson(
|
const fc = planesGeoJson(
|
||||||
snapshot({
|
snapshot({
|
||||||
planes: [
|
planes: [
|
||||||
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'x', destIcao: null, destName: null, departureSimTime: 0, lat: 0, lon: 0 },
|
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'x', destIcao: null, destName: null, departureSimTime: 0, lat: 0, lon: 0, queue: [] },
|
||||||
],
|
],
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -89,7 +89,7 @@ describe('routesGeoJson (v0.12.0 — one line per flying plane\'s current leg)',
|
|||||||
const fc = routesGeoJson(
|
const fc = routesGeoJson(
|
||||||
snapshot({
|
snapshot({
|
||||||
planes: [
|
planes: [
|
||||||
{ id: 'p1', model: 'atr72', status: 'available', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', destIcao: null, destName: null, departureSimTime: null, lat: 50.03, lon: 8.56 },
|
{ id: 'p1', model: 'atr72', status: 'available', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', destIcao: null, destName: null, departureSimTime: null, lat: 50.03, lon: 8.56, queue: [] },
|
||||||
],
|
],
|
||||||
}),
|
}),
|
||||||
AIRPORTS,
|
AIRPORTS,
|
||||||
@@ -101,7 +101,7 @@ describe('routesGeoJson (v0.12.0 — one line per flying plane\'s current leg)',
|
|||||||
const fc = routesGeoJson(
|
const fc = routesGeoJson(
|
||||||
snapshot({
|
snapshot({
|
||||||
planes: [
|
planes: [
|
||||||
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', destIcao: 'EHAM', destName: 'A', departureSimTime: 0, lat: 51, lon: 9 },
|
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', destIcao: 'EHAM', destName: 'A', departureSimTime: 0, lat: 51, lon: 9, queue: [] },
|
||||||
],
|
],
|
||||||
}),
|
}),
|
||||||
AIRPORTS,
|
AIRPORTS,
|
||||||
@@ -118,7 +118,7 @@ describe('routesGeoJson (v0.12.0 — one line per flying plane\'s current leg)',
|
|||||||
const fc = routesGeoJson(
|
const fc = routesGeoJson(
|
||||||
snapshot({
|
snapshot({
|
||||||
planes: [
|
planes: [
|
||||||
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'ZZZZ', locationName: '?', destIcao: 'EDDV', destName: 'H', departureSimTime: 0, lat: 0, lon: 0 },
|
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'ZZZZ', locationName: '?', destIcao: 'EDDV', destName: 'H', departureSimTime: 0, lat: 0, lon: 0, queue: [] },
|
||||||
],
|
],
|
||||||
}),
|
}),
|
||||||
AIRPORTS,
|
AIRPORTS,
|
||||||
@@ -130,8 +130,8 @@ describe('routesGeoJson (v0.12.0 — one line per flying plane\'s current leg)',
|
|||||||
const fc = routesGeoJson(
|
const fc = routesGeoJson(
|
||||||
snapshot({
|
snapshot({
|
||||||
planes: [
|
planes: [
|
||||||
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', destIcao: 'EDDV', destName: 'H', departureSimTime: 0, lat: 51, lon: 9 },
|
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', destIcao: 'EDDV', destName: 'H', departureSimTime: 0, lat: 51, lon: 9, queue: [] },
|
||||||
{ id: 'p2', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDV', locationName: 'H', destIcao: 'EHAM', destName: 'A', departureSimTime: 0, lat: 52.4, lon: 9.6 },
|
{ id: 'p2', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDV', locationName: 'H', destIcao: 'EHAM', destName: 'A', departureSimTime: 0, lat: 52.4, lon: 9.6, queue: [] },
|
||||||
],
|
],
|
||||||
}),
|
}),
|
||||||
AIRPORTS,
|
AIRPORTS,
|
||||||
@@ -140,6 +140,122 @@ describe('routesGeoJson (v0.12.0 — one line per flying plane\'s current leg)',
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('queuedRoutesGeoJson (ISS-043 v0.26.0 — dotted queue line: dest → queued legs only)', () => {
|
||||||
|
it('draws nothing for a grounded plane, even with a non-empty queue', () => {
|
||||||
|
const fc = queuedRoutesGeoJson(
|
||||||
|
[
|
||||||
|
{ id: 'p1', model: 'atr72', status: 'available', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', destIcao: null, destName: null, departureSimTime: null, lat: 50.03, lon: 8.56, queue: ['EHAM'] },
|
||||||
|
],
|
||||||
|
AIRPORTS,
|
||||||
|
);
|
||||||
|
expect(fc.features).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('draws nothing for a flying plane with an empty queue', () => {
|
||||||
|
const fc = queuedRoutesGeoJson(
|
||||||
|
[
|
||||||
|
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', destIcao: 'EHAM', destName: 'A', departureSimTime: 0, lat: 51, lon: 9, queue: [] },
|
||||||
|
],
|
||||||
|
AIRPORTS,
|
||||||
|
);
|
||||||
|
expect(fc.features).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('flying plane with a 2-leg queue → one feature chaining dest → q0 → q1 with exact endpoints', () => {
|
||||||
|
const fc = queuedRoutesGeoJson(
|
||||||
|
[
|
||||||
|
// Active leg EDDF→EHAM stays in routesGeoJson; the queue line is ONLY EHAM → EDDV → LEMD.
|
||||||
|
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', destIcao: 'EHAM', destName: 'A', departureSimTime: 0, lat: 51, lon: 9, queue: ['EDDV', 'LEMD'] },
|
||||||
|
],
|
||||||
|
AIRPORTS,
|
||||||
|
);
|
||||||
|
expect(fc.features).toHaveLength(1);
|
||||||
|
expect(fc.features[0].properties).toEqual({ planeId: 'p1' });
|
||||||
|
const coords = fc.features[0].geometry.coordinates;
|
||||||
|
// Two concatenated arcs with the shared joint point dropped once: n_legs × SEGMENTS + 1 points.
|
||||||
|
expect(coords.length).toBe(2 * ROUTE_ARC_SEGMENTS + 1);
|
||||||
|
expect(coords[0]).toEqual([4.76, 52.31]); // starts at DEST (EHAM), not at the plane's origin
|
||||||
|
expect(coords[coords.length - 1]).toEqual([-3.56, 40.47]); // ends at the last queued airport (LEMD)
|
||||||
|
expect(coords[ROUTE_ARC_SEGMENTS]).toEqual([9.68, 52.46]); // joint point = first queued airport (EDDV), exact
|
||||||
|
});
|
||||||
|
|
||||||
|
it('skips a plane whose dest or a queued ICAO is missing from the airport index', () => {
|
||||||
|
const fc = queuedRoutesGeoJson(
|
||||||
|
[
|
||||||
|
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', destIcao: 'ZZZZ', destName: '?', departureSimTime: 0, lat: 51, lon: 9, queue: ['EHAM'] },
|
||||||
|
{ id: 'p2', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', destIcao: 'EHAM', destName: 'A', departureSimTime: 0, lat: 51, lon: 9, queue: ['ZZZZ'] },
|
||||||
|
],
|
||||||
|
AIRPORTS,
|
||||||
|
);
|
||||||
|
expect(fc.features).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('one feature per qualifying plane — grounded and empty-queue planes draw nothing', () => {
|
||||||
|
const fc = queuedRoutesGeoJson(
|
||||||
|
[
|
||||||
|
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', destIcao: 'EHAM', destName: 'A', departureSimTime: 0, lat: 51, lon: 9, queue: ['LEMD'] },
|
||||||
|
{ id: 'p2', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EHAM', locationName: 'A', destIcao: 'EDDV', destName: 'H', departureSimTime: 0, lat: 52.3, lon: 4.7, queue: [] },
|
||||||
|
{ id: 'p3', model: 'atr72', status: 'available', fuel: 1, maxFuel: 2, locationIcao: 'EDDV', locationName: 'H', destIcao: null, destName: null, departureSimTime: null, lat: 52.46, lon: 9.68, queue: ['LEMD'] },
|
||||||
|
],
|
||||||
|
AIRPORTS,
|
||||||
|
);
|
||||||
|
expect(fc.features.map((f) => f.properties.planeId)).toEqual(['p1']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('hoverRouteGeoJson (ISS-022/025/027 v0.22.0 — hover route trace)', () => {
|
||||||
|
it('returns an empty collection for the no-hover "" sentinel', () => {
|
||||||
|
expect(hoverRouteGeoJson('', '', AIRPORTS)).toEqual({ type: 'FeatureCollection', features: [] });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('draws one great-circle line between two known airports with exact endpoints', () => {
|
||||||
|
const fc = hoverRouteGeoJson('EDDF', 'EHAM', AIRPORTS);
|
||||||
|
expect(fc.features).toHaveLength(1);
|
||||||
|
expect(fc.features[0].properties).toEqual({ planeId: '' }); // pure overlay — no owning plane
|
||||||
|
const coords = fc.features[0].geometry.coordinates;
|
||||||
|
expect(coords.length).toBe(ROUTE_ARC_SEGMENTS + 1); // sampled arc, not a 2-point chord
|
||||||
|
expect(coords[0]).toEqual([8.56, 50.03]); // EDDF [lon, lat] — exact endpoint
|
||||||
|
expect(coords[coords.length - 1]).toEqual([4.76, 52.31]); // EHAM — exact endpoint
|
||||||
|
});
|
||||||
|
|
||||||
|
it('draws the same trace reversed (endpoints swapped, arc mirrored)', () => {
|
||||||
|
const ab = hoverRouteGeoJson('EDDF', 'EHAM', AIRPORTS).features[0].geometry.coordinates;
|
||||||
|
const ba = hoverRouteGeoJson('EHAM', 'EDDF', AIRPORTS).features[0].geometry.coordinates;
|
||||||
|
expect(ba.length).toBe(ab.length);
|
||||||
|
// The slerp is symmetric up to floating-point rounding (1 − t ≠ (N−t)/N bit-exactly), so
|
||||||
|
// compare with a tolerance: each reversed point sits on the forward arc within ~1e-9 degrees.
|
||||||
|
for (let i = 0; i < ab.length; i++) {
|
||||||
|
expect(Math.abs(ba[i][0] - ab[ab.length - 1 - i][0])).toBeLessThan(1e-9);
|
||||||
|
expect(Math.abs(ba[i][1] - ab[ab.length - 1 - i][1])).toBeLessThan(1e-9);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns an empty collection when the from airport is missing from the dataset', () => {
|
||||||
|
expect(hoverRouteGeoJson('ZZZZ', 'EDDV', AIRPORTS)).toEqual({ type: 'FeatureCollection', features: [] });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns an empty collection when the to airport is missing from the dataset', () => {
|
||||||
|
expect(hoverRouteGeoJson('EDDF', 'ZZZZ', AIRPORTS)).toEqual({ type: 'FeatureCollection', features: [] });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('hoverTraceGeoJson (ISS-040 v0.23.2 — on-board package trace from the carrier\'s live position)', () => {
|
||||||
|
it('draws one great-circle line from the given start coord to the dest airport with exact endpoints', () => {
|
||||||
|
const from = { lat: 51.2, lon: 9.1 }; // a mid-flight position — not an airport
|
||||||
|
const fc = hoverTraceGeoJson(from, 'EHAM', AIRPORTS);
|
||||||
|
expect(fc.features).toHaveLength(1);
|
||||||
|
expect(fc.features[0].properties).toEqual({ planeId: '' }); // pure overlay — no owning plane
|
||||||
|
const coords = fc.features[0].geometry.coordinates;
|
||||||
|
expect(coords.length).toBe(ROUTE_ARC_SEGMENTS + 1); // sampled arc, not a 2-point chord
|
||||||
|
expect(coords[0]).toEqual([9.1, 51.2]); // live start — exact endpoint
|
||||||
|
expect(coords[coords.length - 1]).toEqual([4.76, 52.31]); // EHAM — exact endpoint
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns an empty collection when the dest airport is missing from the dataset', () => {
|
||||||
|
expect(hoverTraceGeoJson({ lat: 0, lon: 0 }, 'ZZZZ', AIRPORTS)).toEqual({ type: 'FeatureCollection', features: [] });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('greatCircleArc (v0.12.2 — curved route traces)', () => {
|
describe('greatCircleArc (v0.12.2 — curved route traces)', () => {
|
||||||
it('samples >2 points with the endpoints exactly at the airport coords', () => {
|
it('samples >2 points with the endpoints exactly at the airport coords', () => {
|
||||||
const arc = greatCircleArc(AIRPORTS.get('EDDF')!, AIRPORTS.get('EHAM')!);
|
const arc = greatCircleArc(AIRPORTS.get('EDDF')!, AIRPORTS.get('EHAM')!);
|
||||||
|
|||||||
+82
-1
@@ -1,4 +1,4 @@
|
|||||||
import type { StateSnapshot } from './game/state';
|
import type { PlaneState, StateSnapshot } from './game/state';
|
||||||
import { formatFuel } from './format';
|
import { formatFuel } from './format';
|
||||||
import { positionAt } from './sim/movement';
|
import { positionAt } from './sim/movement';
|
||||||
|
|
||||||
@@ -85,6 +85,59 @@ export function greatCircleArc(from: AirportCoord, to: AirportCoord): [number, n
|
|||||||
return coords;
|
return coords;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ISS-022/025/027 (v0.22.0): the hover route trace — one great-circle LineString between two
|
||||||
|
// airports, drawn top-most while a panel row hovers (job-list rows, on-board cargo rows, the
|
||||||
|
// Relocate section). Empty collection when either endpoint is missing from the dataset — never
|
||||||
|
// guessed; the '' sentinel (no hovered target) resolves to nothing and yields the same.
|
||||||
|
export function hoverRouteGeoJson(
|
||||||
|
fromIcao: string,
|
||||||
|
toIcao: string,
|
||||||
|
airportsByIcao: ReadonlyMap<string, AirportCoord>,
|
||||||
|
): FeatureCollection<MapLineFeature> {
|
||||||
|
const from = airportsByIcao.get(fromIcao);
|
||||||
|
const to = airportsByIcao.get(toIcao);
|
||||||
|
if (!from || !to) return EMPTY_LINES;
|
||||||
|
return {
|
||||||
|
type: 'FeatureCollection',
|
||||||
|
features: [
|
||||||
|
{
|
||||||
|
type: 'Feature',
|
||||||
|
geometry: {
|
||||||
|
type: 'LineString',
|
||||||
|
coordinates: greatCircleArc(from, to),
|
||||||
|
},
|
||||||
|
properties: { planeId: '' }, // no owning plane — a pure hover overlay
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ISS-040 (v0.23.2): the on-board package hover trace — same shape as hoverRouteGeoJson but the
|
||||||
|
// start is a live COORDINATE (the carrier plane's current position), not an airport ICAO: once the
|
||||||
|
// plane has departed with cargo still loaded, the preview must begin where it actually is. Empty
|
||||||
|
// collection when the destination is missing from the dataset — never guessed.
|
||||||
|
export function hoverTraceGeoJson(
|
||||||
|
from: AirportCoord,
|
||||||
|
toIcao: string,
|
||||||
|
airportsByIcao: ReadonlyMap<string, AirportCoord>,
|
||||||
|
): FeatureCollection<MapLineFeature> {
|
||||||
|
const to = airportsByIcao.get(toIcao);
|
||||||
|
if (!to) return EMPTY_LINES;
|
||||||
|
return {
|
||||||
|
type: 'FeatureCollection',
|
||||||
|
features: [
|
||||||
|
{
|
||||||
|
type: 'Feature',
|
||||||
|
geometry: {
|
||||||
|
type: 'LineString',
|
||||||
|
coordinates: greatCircleArc(from, to),
|
||||||
|
},
|
||||||
|
properties: { planeId: '' }, // no owning plane — a pure hover overlay
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// One LineString per FLYING plane — its current leg from locationIcao to dest_icao.
|
// One LineString per FLYING plane — its current leg from locationIcao to dest_icao.
|
||||||
// Grounded planes draw nothing; a flying plane missing either endpoint from the
|
// Grounded planes draw nothing; a flying plane missing either endpoint from the
|
||||||
// dataset is skipped, never guessed. The line is sampled along the great circle
|
// dataset is skipped, never guessed. The line is sampled along the great circle
|
||||||
@@ -111,3 +164,31 @@ export function routesGeoJson(
|
|||||||
}
|
}
|
||||||
return { type: 'FeatureCollection', features };
|
return { type: 'FeatureCollection', features };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ISS-043 (v0.26.0): the dotted queue line — one LineString per FLYING plane with a non-empty
|
||||||
|
// queue, chaining dest → queue[0] → … → queue[n−1]: ONLY the not-yet-started legs (the active
|
||||||
|
// leg locationIcao→dest stays in routesGeoJson's solid layer). Arcs are concatenated with the
|
||||||
|
// shared joint point dropped once. A plane is skipped — never guessed — when its dest or any
|
||||||
|
// queued ICAO is missing from the airport index; empty collection when nothing qualifies.
|
||||||
|
export function queuedRoutesGeoJson(
|
||||||
|
planes: PlaneState[],
|
||||||
|
airportsByIcao: ReadonlyMap<string, AirportCoord>,
|
||||||
|
): FeatureCollection<MapLineFeature> {
|
||||||
|
const features: MapLineFeature[] = [];
|
||||||
|
for (const p of planes) {
|
||||||
|
if (p.status !== 'flying' || !p.destIcao || p.queue.length === 0) continue;
|
||||||
|
const pts = [p.destIcao, ...p.queue].map((icao) => airportsByIcao.get(icao));
|
||||||
|
if (pts.some((c) => c === undefined)) continue; // an endpoint is missing from the dataset — skip
|
||||||
|
const coords: [number, number][] = [];
|
||||||
|
for (let i = 0; i < pts.length - 1; i++) {
|
||||||
|
const arc = greatCircleArc(pts[i]!, pts[i + 1]!);
|
||||||
|
coords.push(...(i === 0 ? arc : arc.slice(1))); // drop the duplicated joint point
|
||||||
|
}
|
||||||
|
features.push({
|
||||||
|
type: 'Feature',
|
||||||
|
geometry: { type: 'LineString', coordinates: coords },
|
||||||
|
properties: { planeId: p.id },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return { type: 'FeatureCollection', features };
|
||||||
|
}
|
||||||
|
|||||||
+51
-10
@@ -3,14 +3,17 @@ import { describe, expect, it } from 'vitest';
|
|||||||
import { openApiSpec } from './openapi';
|
import { openApiSpec } from './openapi';
|
||||||
|
|
||||||
describe('OpenAPI spec', () => {
|
describe('OpenAPI spec', () => {
|
||||||
it('documents exactly the ten public endpoints (4 read + 6 player actions)', () => {
|
it('documents exactly the thirteen public endpoints (4 read + 9 player actions)', () => {
|
||||||
expect(Object.keys(openApiSpec.paths).sort()).toEqual([
|
expect(Object.keys(openApiSpec.paths).sort()).toEqual([
|
||||||
'/api/airports',
|
'/api/airports',
|
||||||
'/api/market/buy-plane',
|
'/api/market/buy-plane',
|
||||||
'/api/market/sell-plane',
|
'/api/market/sell-plane',
|
||||||
'/api/packages/{id}/abandon',
|
'/api/packages/{id}/abandon',
|
||||||
|
'/api/packages/{id}/ignore', // v0.29.0 (ISS-047 part B)
|
||||||
'/api/packages/{id}/load',
|
'/api/packages/{id}/load',
|
||||||
'/api/planes/{planeId}/fly',
|
'/api/planes/{planeId}/fly',
|
||||||
|
'/api/planes/{planeId}/queue', // v0.25.0 (ISS-043)
|
||||||
|
'/api/planes/{planeId}/queue/cancel', // v0.25.0 (ISS-043)
|
||||||
'/api/planes/{planeId}/refuel',
|
'/api/planes/{planeId}/refuel',
|
||||||
'/api/sim',
|
'/api/sim',
|
||||||
'/api/state',
|
'/api/state',
|
||||||
@@ -90,11 +93,19 @@ describe('OpenAPI spec', () => {
|
|||||||
expect(snap.sellFraction.type).toBe('number');
|
expect(snap.sellFraction.type).toBe('number');
|
||||||
|
|
||||||
const catalog = openApiSpec.components.schemas.CatalogEntry.properties;
|
const catalog = openApiSpec.components.schemas.CatalogEntry.properties;
|
||||||
expect(Object.keys(catalog).sort()).toEqual(['burnPerKm', 'capacity', 'label', 'maxFuel', 'model', 'price', 'speedKmh']);
|
expect(Object.keys(catalog).sort()).toEqual([
|
||||||
for (const key of ['burnPerKm', 'maxFuel', 'price', 'speedKmh'] as const) {
|
'burnPerKm',
|
||||||
|
'emptyWeightKg', // v0.16.0 weighted burn model input
|
||||||
|
'label',
|
||||||
|
'maxFuel',
|
||||||
|
'maxPayloadKg', // v0.27.0 (ISS-045) — replaces the v0.12.0 slot capacity
|
||||||
|
'model',
|
||||||
|
'price',
|
||||||
|
'speedKmh',
|
||||||
|
]);
|
||||||
|
for (const key of ['burnPerKm', 'emptyWeightKg', 'maxFuel', 'maxPayloadKg', 'price', 'speedKmh'] as const) {
|
||||||
expect(catalog[key].type, `CatalogEntry.${key}`).toBe('number');
|
expect(catalog[key].type, `CatalogEntry.${key}`).toBe('number');
|
||||||
}
|
}
|
||||||
expect(catalog.capacity.type).toBe('integer'); // v0.12.0 slot capacity
|
|
||||||
expect(catalog.model.type).toBe('string');
|
expect(catalog.model.type).toBe('string');
|
||||||
expect(catalog.label.type).toBe('string');
|
expect(catalog.label.type).toBe('string');
|
||||||
|
|
||||||
@@ -111,6 +122,7 @@ describe('OpenAPI spec', () => {
|
|||||||
'lon',
|
'lon',
|
||||||
'maxFuel',
|
'maxFuel',
|
||||||
'model',
|
'model',
|
||||||
|
'queue', // v0.25.0 (ISS-043) — upcoming legs not yet started
|
||||||
'status',
|
'status',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -128,13 +140,14 @@ describe('OpenAPI spec', () => {
|
|||||||
'planeId',
|
'planeId',
|
||||||
'reward',
|
'reward',
|
||||||
'status',
|
'status',
|
||||||
|
'weightKg', // v0.27.0 (ISS-045) — package weight in kg
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const sim = openApiSpec.components.schemas.SimState.properties;
|
const sim = openApiSpec.components.schemas.SimState.properties;
|
||||||
expect(Object.keys(sim).sort()).toEqual(['clockMs', 'paused', 'timeScale']);
|
expect(Object.keys(sim).sort()).toEqual(['clockMs', 'paused', 'timeScale']);
|
||||||
|
|
||||||
const packageStatus = openApiSpec.components.schemas.PackageState.properties.status;
|
const packageStatus = openApiSpec.components.schemas.PackageState.properties.status;
|
||||||
expect(packageStatus.enum.sort()).toEqual(['abandoned', 'delivered', 'expired', 'loaded', 'open']);
|
expect(packageStatus.enum.sort()).toEqual(['abandoned', 'delivered', 'expired', 'ignored', 'loaded', 'open']); // v0.29.0 (ISS-047 part B)
|
||||||
});
|
});
|
||||||
|
|
||||||
it('describes POST /api/sim as SimControlsRequest → SimState with a 400 error shape', () => {
|
it('describes POST /api/sim as SimControlsRequest → SimState with a 400 error shape', () => {
|
||||||
@@ -160,12 +173,12 @@ describe('OpenAPI spec', () => {
|
|||||||
expect(Object.keys(error)).toEqual(['error']);
|
expect(Object.keys(error)).toEqual(['error']);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('documents the six action endpoints: snapshot on 200, Error on their 4xx paths', () => {
|
it('documents the eight action endpoints: snapshot on 200, Error on their 4xx paths', () => {
|
||||||
// The spec object is a literal type; these helpers view it as plain JSON.
|
// The spec object is a literal type; these helpers view it as plain JSON.
|
||||||
const post = (p: string) =>
|
const post = (p: string) =>
|
||||||
((openApiSpec.paths as Record<string, { post?: unknown }>)[p]?.post ?? {}) as {
|
((openApiSpec.paths as Record<string, { post?: unknown }>)[p]?.post ?? {}) as {
|
||||||
responses: Record<string, unknown>;
|
responses: Record<string, unknown>;
|
||||||
requestBody?: { content: Record<string, { schema: { $ref: string } }> };
|
requestBody?: { required?: boolean; content: Record<string, { schema: { $ref: string } }> };
|
||||||
parameters?: Array<{ name: string }>;
|
parameters?: Array<{ name: string }>;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -174,6 +187,8 @@ describe('OpenAPI spec', () => {
|
|||||||
'/api/packages/{id}/load',
|
'/api/packages/{id}/load',
|
||||||
'/api/packages/{id}/abandon',
|
'/api/packages/{id}/abandon',
|
||||||
'/api/planes/{planeId}/fly',
|
'/api/planes/{planeId}/fly',
|
||||||
|
'/api/planes/{planeId}/queue', // v0.25.0 (ISS-043)
|
||||||
|
'/api/planes/{planeId}/queue/cancel', // v0.25.0 (ISS-043)
|
||||||
'/api/market/buy-plane',
|
'/api/market/buy-plane',
|
||||||
'/api/market/sell-plane',
|
'/api/market/sell-plane',
|
||||||
'/api/planes/{planeId}/refuel',
|
'/api/planes/{planeId}/refuel',
|
||||||
@@ -187,17 +202,26 @@ describe('OpenAPI spec', () => {
|
|||||||
expect(errorCodes('/api/packages/{id}/load')).toEqual(['400', '404', '409']);
|
expect(errorCodes('/api/packages/{id}/load')).toEqual(['400', '404', '409']);
|
||||||
expect(errorCodes('/api/packages/{id}/abandon')).toEqual(['404', '409']);
|
expect(errorCodes('/api/packages/{id}/abandon')).toEqual(['404', '409']);
|
||||||
expect(errorCodes('/api/planes/{planeId}/fly')).toEqual(['400', '404', '409']);
|
expect(errorCodes('/api/planes/{planeId}/fly')).toEqual(['400', '404', '409']);
|
||||||
|
expect(errorCodes('/api/planes/{planeId}/queue')).toEqual(['400', '404']); // v0.25.0 — no 409: queueing works grounded or flying
|
||||||
|
expect(errorCodes('/api/planes/{planeId}/queue/cancel')).toEqual(['400', '404']); // v0.25.0
|
||||||
expect(errorCodes('/api/market/buy-plane')).toEqual(['400', '409']);
|
expect(errorCodes('/api/market/buy-plane')).toEqual(['400', '409']);
|
||||||
expect(errorCodes('/api/market/sell-plane')).toEqual(['400', '404', '409']);
|
expect(errorCodes('/api/market/sell-plane')).toEqual(['400', '404', '409']);
|
||||||
expect(errorCodes('/api/planes/{planeId}/refuel')).toEqual(['404', '409']);
|
expect(errorCodes('/api/planes/{planeId}/refuel')).toEqual(['400', '404', '409']); // v0.16.0 optional body
|
||||||
|
|
||||||
// Request bodies: load/fly/buy/sell take their dedicated schemas; abandon/refuel take none.
|
// Request bodies: load/fly/buy/sell take their dedicated schemas; abandon takes none;
|
||||||
|
// refuel's is OPTIONAL (v0.16.0) — no body still means "fill to full".
|
||||||
expect(post('/api/packages/{id}/load').requestBody?.content['application/json'].schema.$ref).toBe(
|
expect(post('/api/packages/{id}/load').requestBody?.content['application/json'].schema.$ref).toBe(
|
||||||
'#/components/schemas/LoadPackageRequest',
|
'#/components/schemas/LoadPackageRequest',
|
||||||
);
|
);
|
||||||
expect(post('/api/planes/{planeId}/fly').requestBody?.content['application/json'].schema.$ref).toBe(
|
expect(post('/api/planes/{planeId}/fly').requestBody?.content['application/json'].schema.$ref).toBe(
|
||||||
'#/components/schemas/FlyPlaneRequest',
|
'#/components/schemas/FlyPlaneRequest',
|
||||||
);
|
);
|
||||||
|
expect(post('/api/planes/{planeId}/queue').requestBody?.content['application/json'].schema.$ref).toBe(
|
||||||
|
'#/components/schemas/QueueLegRequest', // v0.25.0 (ISS-043)
|
||||||
|
);
|
||||||
|
expect(post('/api/planes/{planeId}/queue/cancel').requestBody?.content['application/json'].schema.$ref).toBe(
|
||||||
|
'#/components/schemas/CancelQueuedLegRequest', // v0.25.0 (ISS-043)
|
||||||
|
);
|
||||||
expect(post('/api/market/buy-plane').requestBody?.content['application/json'].schema.$ref).toBe(
|
expect(post('/api/market/buy-plane').requestBody?.content['application/json'].schema.$ref).toBe(
|
||||||
'#/components/schemas/BuyPlaneRequest',
|
'#/components/schemas/BuyPlaneRequest',
|
||||||
);
|
);
|
||||||
@@ -205,13 +229,17 @@ describe('OpenAPI spec', () => {
|
|||||||
'#/components/schemas/SellPlaneRequest',
|
'#/components/schemas/SellPlaneRequest',
|
||||||
);
|
);
|
||||||
expect(post('/api/packages/{id}/abandon').requestBody).toBeUndefined();
|
expect(post('/api/packages/{id}/abandon').requestBody).toBeUndefined();
|
||||||
expect(post('/api/planes/{planeId}/refuel').requestBody).toBeUndefined();
|
const refuelBody = post('/api/planes/{planeId}/refuel').requestBody;
|
||||||
|
expect(refuelBody?.content['application/json'].schema.$ref).toBe('#/components/schemas/RefuelRequest');
|
||||||
|
expect(refuelBody?.required).toBe(false); // optional — no body still means "fill to full"
|
||||||
|
|
||||||
// Path parameters are declared on the parameterized routes.
|
// Path parameters are declared on the parameterized routes.
|
||||||
const paramNames = (p: string) => post(p).parameters?.map((x) => x.name);
|
const paramNames = (p: string) => post(p).parameters?.map((x) => x.name);
|
||||||
expect(paramNames('/api/packages/{id}/load')).toEqual(['id']);
|
expect(paramNames('/api/packages/{id}/load')).toEqual(['id']);
|
||||||
expect(paramNames('/api/packages/{id}/abandon')).toEqual(['id']);
|
expect(paramNames('/api/packages/{id}/abandon')).toEqual(['id']);
|
||||||
expect(paramNames('/api/planes/{planeId}/fly')).toEqual(['planeId']);
|
expect(paramNames('/api/planes/{planeId}/fly')).toEqual(['planeId']);
|
||||||
|
expect(paramNames('/api/planes/{planeId}/queue')).toEqual(['planeId']); // v0.25.0 (ISS-043)
|
||||||
|
expect(paramNames('/api/planes/{planeId}/queue/cancel')).toEqual(['planeId']); // v0.25.0 (ISS-043)
|
||||||
expect(paramNames('/api/planes/{planeId}/refuel')).toEqual(['planeId']);
|
expect(paramNames('/api/planes/{planeId}/refuel')).toEqual(['planeId']);
|
||||||
|
|
||||||
// Request schema shapes.
|
// Request schema shapes.
|
||||||
@@ -221,11 +249,24 @@ describe('OpenAPI spec', () => {
|
|||||||
const fly = openApiSpec.components.schemas.FlyPlaneRequest;
|
const fly = openApiSpec.components.schemas.FlyPlaneRequest;
|
||||||
expect(fly.required).toEqual(['destIcao']);
|
expect(fly.required).toEqual(['destIcao']);
|
||||||
expect(fly.properties.destIcao.type).toBe('string');
|
expect(fly.properties.destIcao.type).toBe('string');
|
||||||
|
// v0.25.0 (ISS-043): the queue request schemas mirror fly's destIcao shape.
|
||||||
|
const queueLeg = openApiSpec.components.schemas.QueueLegRequest;
|
||||||
|
expect(queueLeg.required).toEqual(['destIcao']);
|
||||||
|
expect(queueLeg.properties.destIcao.type).toBe('string');
|
||||||
|
const cancelQueuedLeg = openApiSpec.components.schemas.CancelQueuedLegRequest;
|
||||||
|
expect(cancelQueuedLeg.required).toEqual(['index']);
|
||||||
|
expect(cancelQueuedLeg.properties.index.type).toBe('integer');
|
||||||
const buy = openApiSpec.components.schemas.BuyPlaneRequest;
|
const buy = openApiSpec.components.schemas.BuyPlaneRequest;
|
||||||
expect(buy.required).toEqual(['model']);
|
expect(buy.required).toEqual(['model']);
|
||||||
expect(buy.properties.model.type).toBe('string');
|
expect(buy.properties.model.type).toBe('string');
|
||||||
const sell = openApiSpec.components.schemas.SellPlaneRequest;
|
const sell = openApiSpec.components.schemas.SellPlaneRequest;
|
||||||
expect(sell.required).toEqual(['planeId']);
|
expect(sell.required).toEqual(['planeId']);
|
||||||
expect(sell.properties.planeId.type).toBe('string');
|
expect(sell.properties.planeId.type).toBe('string');
|
||||||
|
|
||||||
|
// RefuelRequest (v0.16.0): both fields optional — no body / {} means "full".
|
||||||
|
const refuel = openApiSpec.components.schemas.RefuelRequest;
|
||||||
|
expect((refuel as { required?: string[] }).required ?? []).toEqual([]);
|
||||||
|
expect(((refuel.properties.mode) as { enum: string[] }).enum.sort()).toEqual(['forFlight', 'full']);
|
||||||
|
expect(refuel.properties.packageId.type).toBe('string');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+159
-11
@@ -106,7 +106,7 @@ export const openApiSpec = {
|
|||||||
post: {
|
post: {
|
||||||
summary: 'Load a package onto a plane',
|
summary: 'Load a package onto a plane',
|
||||||
description:
|
description:
|
||||||
'Bind an OPEN package to a GROUNDED ("available") plane at the package\'s origin (v0.12.0). The plane needs a free slot — capacity per catalog model; expired packages still occupy theirs. The sim clock is ticked first, so the returned snapshot reflects current game time.',
|
'Bind an OPEN package to a GROUNDED ("available") plane at the package\'s origin (v0.12.0). The plane needs enough payload room for the package weight — maxPayloadKg per catalog model; expired packages still occupy theirs (v0.27.0). The sim clock is ticked first, so the returned snapshot reflects current game time.',
|
||||||
operationId: 'loadPackage',
|
operationId: 'loadPackage',
|
||||||
parameters: [
|
parameters: [
|
||||||
{ name: 'id', in: 'path', required: true, schema: { type: 'string' } },
|
{ name: 'id', in: 'path', required: true, schema: { type: 'string' } },
|
||||||
@@ -165,6 +165,31 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
'/api/packages/{id}/ignore': {
|
||||||
|
post: {
|
||||||
|
summary: 'Ignore an open job',
|
||||||
|
description:
|
||||||
|
'Dismiss an OPEN job so it leaves the market permanently (v0.29.0, ISS-047 part B). No penalty and nothing else changes — the top-up logic spawns a replacement on the next tick. No body.',
|
||||||
|
operationId: 'ignorePackage',
|
||||||
|
parameters: [
|
||||||
|
{ name: 'id', in: 'path', required: true, schema: { type: 'string' } },
|
||||||
|
],
|
||||||
|
responses: {
|
||||||
|
200: {
|
||||||
|
description: 'Ignored — full state snapshot (package "ignored", gone from the open list)',
|
||||||
|
content: { 'application/json': { schema: { $ref: '#/components/schemas/StateSnapshot' } } },
|
||||||
|
},
|
||||||
|
404: {
|
||||||
|
description: 'Unknown package id',
|
||||||
|
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||||
|
},
|
||||||
|
409: {
|
||||||
|
description: 'Package not "open"',
|
||||||
|
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
'/api/planes/{planeId}/fly': {
|
'/api/planes/{planeId}/fly': {
|
||||||
post: {
|
post: {
|
||||||
summary: 'Fly a plane to an airport',
|
summary: 'Fly a plane to an airport',
|
||||||
@@ -197,7 +222,76 @@ export const openApiSpec = {
|
|||||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||||
},
|
},
|
||||||
409: {
|
409: {
|
||||||
description: 'Plane not grounded, or insufficient fuel for the leg (burnPerKm × great-circle km)',
|
description:
|
||||||
|
'Plane not grounded, or insufficient fuel for the leg (v0.16.0 weight-proportional burn — the fuel required to cover the great-circle distance arriving empty)',
|
||||||
|
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
'/api/planes/{planeId}/queue': {
|
||||||
|
post: {
|
||||||
|
summary: 'Queue a flight leg for a plane',
|
||||||
|
description:
|
||||||
|
'Append a NOT-yet-started leg to the plane\'s flight queue (v0.25.0, ISS-043). Works whether the plane is grounded or flying — you can pre-build a route; the active leg still starts via /fly and nothing auto-starts here. On landing, the engine auto-chains the first queued leg when fuel covers it (otherwise the plane grounds with the queue kept intact for refuel + re-dispatch).',
|
||||||
|
operationId: 'queueLeg',
|
||||||
|
parameters: [
|
||||||
|
{ name: 'planeId', in: 'path', required: true, schema: { type: 'string' } },
|
||||||
|
],
|
||||||
|
requestBody: {
|
||||||
|
required: true,
|
||||||
|
content: {
|
||||||
|
'application/json': {
|
||||||
|
schema: { $ref: '#/components/schemas/QueueLegRequest' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
responses: {
|
||||||
|
200: {
|
||||||
|
description: 'Queued — full state snapshot (plane.queue now includes the new leg)',
|
||||||
|
content: { 'application/json': { schema: { $ref: '#/components/schemas/StateSnapshot' } } },
|
||||||
|
},
|
||||||
|
400: {
|
||||||
|
description:
|
||||||
|
'Invalid body (not an object, unknown field, or missing/non-string destIcao) or the ICAO is not in the airport dataset',
|
||||||
|
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||||
|
},
|
||||||
|
404: {
|
||||||
|
description: 'Unknown plane id',
|
||||||
|
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
'/api/planes/{planeId}/queue/cancel': {
|
||||||
|
post: {
|
||||||
|
summary: 'Cancel a queued flight leg',
|
||||||
|
description:
|
||||||
|
'Remove a NOT-yet-started leg from the plane\'s queue by index (v0.25.0, ISS-043). Only queued legs are cancellable — the active in-flight leg (destIcao) is never affected.',
|
||||||
|
operationId: 'cancelQueuedLeg',
|
||||||
|
parameters: [
|
||||||
|
{ name: 'planeId', in: 'path', required: true, schema: { type: 'string' } },
|
||||||
|
],
|
||||||
|
requestBody: {
|
||||||
|
required: true,
|
||||||
|
content: {
|
||||||
|
'application/json': {
|
||||||
|
schema: { $ref: '#/components/schemas/CancelQueuedLegRequest' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
responses: {
|
||||||
|
200: {
|
||||||
|
description: 'Cancelled — full state snapshot (plane.queue without the removed leg)',
|
||||||
|
content: { 'application/json': { schema: { $ref: '#/components/schemas/StateSnapshot' } } },
|
||||||
|
},
|
||||||
|
400: {
|
||||||
|
description:
|
||||||
|
'Invalid body (not an object, unknown field, or non-integer index) or the index is outside [0, queue.length)',
|
||||||
|
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||||
|
},
|
||||||
|
404: {
|
||||||
|
description: 'Unknown plane id',
|
||||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -271,22 +365,35 @@ export const openApiSpec = {
|
|||||||
post: {
|
post: {
|
||||||
summary: 'Refuel a grounded plane',
|
summary: 'Refuel a grounded plane',
|
||||||
description:
|
description:
|
||||||
'Fill a grounded plane to maxFuel (v0.8.0). Cost = (maxFuel − fuel) × fuel price per liter, deducted from cash; no body.',
|
'Refuel a grounded plane at the fuel price per added liter, deducted from cash (v0.8.0). The body is optional (v0.16.0): no body or mode "full" fills to maxFuel; mode "forFlight" with packageId adds just enough for that loaded package\'s destination leg — liters = required fuel for the great-circle distance (weight-proportional burn model) minus what is already in the tank.',
|
||||||
operationId: 'refuelPlane',
|
operationId: 'refuelPlane',
|
||||||
parameters: [
|
parameters: [
|
||||||
{ name: 'planeId', in: 'path', required: true, schema: { type: 'string' } },
|
{ name: 'planeId', in: 'path', required: true, schema: { type: 'string' } },
|
||||||
],
|
],
|
||||||
|
requestBody: {
|
||||||
|
required: false,
|
||||||
|
content: {
|
||||||
|
'application/json': {
|
||||||
|
schema: { $ref: '#/components/schemas/RefuelRequest' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
responses: {
|
responses: {
|
||||||
200: {
|
200: {
|
||||||
description: 'Refueled — full state snapshot (fuel at max, cash reduced by the cost)',
|
description: 'Refueled — full state snapshot (fuel raised by exactly the added liters, cash reduced by the cost)',
|
||||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/StateSnapshot' } } },
|
content: { 'application/json': { schema: { $ref: '#/components/schemas/StateSnapshot' } } },
|
||||||
},
|
},
|
||||||
|
400: {
|
||||||
|
description: 'Invalid body (not an object, unknown field, unknown mode, or forFlight without packageId)',
|
||||||
|
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||||
|
},
|
||||||
404: {
|
404: {
|
||||||
description: 'Unknown plane id',
|
description: 'Unknown plane id (or unknown package id in forFlight mode)',
|
||||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||||
},
|
},
|
||||||
409: {
|
409: {
|
||||||
description: 'Plane is flying, or cash is insufficient for the fill-up',
|
description:
|
||||||
|
'Plane is flying, the package is not loaded on this plane (or is expired), the leg does not fit a full tank, or cash is insufficient for the refuel',
|
||||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -376,11 +483,12 @@ export const openApiSpec = {
|
|||||||
label: { type: 'string', description: 'Display name (e.g. "ATR 72-600").' },
|
label: { type: 'string', description: 'Display name (e.g. "ATR 72-600").' },
|
||||||
price: { type: 'number', description: 'Market price in € (buy cost; sell pays out sellFraction × this).' },
|
price: { type: 'number', description: 'Market price in € (buy cost; sell pays out sellFraction × this).' },
|
||||||
maxFuel: { type: 'number', description: 'Fuel capacity, liters.' },
|
maxFuel: { type: 'number', description: 'Fuel capacity, liters.' },
|
||||||
burnPerKm: { type: 'number', description: 'Cruise fuel burn, liters/km.' },
|
burnPerKm: { type: 'number', description: 'Cruise fuel burn at a full tank, liters/km (v0.16.0 weighted model calibrates to this).' },
|
||||||
|
emptyWeightKg: { type: 'number', description: 'Operating empty weight, kg — with burnPerKm and maxFuel it drives the v0.16.0 weight-proportional burn model.' },
|
||||||
speedKmh: { type: 'number', description: 'Cruise speed, km/h.' },
|
speedKmh: { type: 'number', description: 'Cruise speed, km/h.' },
|
||||||
capacity: { type: 'integer', description: 'Cargo slot capacity — packages that can be loaded on one plane (v0.12.0).' },
|
maxPayloadKg: { type: 'number', description: 'Max payload in kg — total package weight that can be loaded on one plane (v0.27.0, replaces the v0.12.0 slot count).' },
|
||||||
},
|
},
|
||||||
required: ['model', 'label', 'price', 'maxFuel', 'burnPerKm', 'speedKmh', 'capacity'],
|
required: ['model', 'label', 'price', 'maxFuel', 'burnPerKm', 'emptyWeightKg', 'speedKmh', 'maxPayloadKg'],
|
||||||
},
|
},
|
||||||
AccountState: {
|
AccountState: {
|
||||||
type: 'object',
|
type: 'object',
|
||||||
@@ -415,7 +523,7 @@ export const openApiSpec = {
|
|||||||
LoadPackageRequest: {
|
LoadPackageRequest: {
|
||||||
type: 'object',
|
type: 'object',
|
||||||
properties: {
|
properties: {
|
||||||
planeId: { type: 'string', description: 'A GROUNDED ("available") plane at the package\'s origin with a free slot.' },
|
planeId: { type: 'string', description: 'A GROUNDED ("available") plane at the package\'s origin with enough payload room for it (v0.27.0).' },
|
||||||
},
|
},
|
||||||
required: ['planeId'],
|
required: ['planeId'],
|
||||||
},
|
},
|
||||||
@@ -426,6 +534,20 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
required: ['destIcao'],
|
required: ['destIcao'],
|
||||||
},
|
},
|
||||||
|
QueueLegRequest: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
destIcao: { type: 'string', description: 'Any airport ICAO from the dataset — appended to the queue as a not-yet-started leg (v0.25.0).' },
|
||||||
|
},
|
||||||
|
required: ['destIcao'],
|
||||||
|
},
|
||||||
|
CancelQueuedLegRequest: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
index: { type: 'integer', description: 'Zero-based position of the queued (not-yet-started) leg to remove; must be within [0, queue.length) (v0.25.0).' },
|
||||||
|
},
|
||||||
|
required: ['index'],
|
||||||
|
},
|
||||||
BuyPlaneRequest: {
|
BuyPlaneRequest: {
|
||||||
type: 'object',
|
type: 'object',
|
||||||
properties: {
|
properties: {
|
||||||
@@ -440,6 +562,22 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
required: ['planeId'],
|
required: ['planeId'],
|
||||||
},
|
},
|
||||||
|
RefuelRequest: {
|
||||||
|
type: 'object',
|
||||||
|
description:
|
||||||
|
'Optional refuel body (v0.16.0) — omit it entirely or send {} to fill the tank; both fields are optional.',
|
||||||
|
properties: {
|
||||||
|
mode: {
|
||||||
|
enum: ['full', 'forFlight'],
|
||||||
|
description:
|
||||||
|
'"full" (default) fills the tank to maxFuel; "forFlight" adds just enough fuel for one loaded package\'s destination leg.',
|
||||||
|
},
|
||||||
|
packageId: {
|
||||||
|
type: 'string',
|
||||||
|
description: 'Required with mode "forFlight": a package LOADED on this plane — its destIcao is the refuel target.',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
Error: {
|
Error: {
|
||||||
type: 'object',
|
type: 'object',
|
||||||
properties: {
|
properties: {
|
||||||
@@ -471,6 +609,12 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
lat: { type: 'number' },
|
lat: { type: 'number' },
|
||||||
lon: { type: 'number' },
|
lon: { type: 'number' },
|
||||||
|
queue: {
|
||||||
|
type: 'array',
|
||||||
|
items: { type: 'string' },
|
||||||
|
description:
|
||||||
|
'Upcoming flight legs NOT yet started (v0.25.0) — ordered ICAOs; the active leg is destIcao. The engine auto-chains queue[0] on landing when fuel covers it.',
|
||||||
|
},
|
||||||
},
|
},
|
||||||
required: [
|
required: [
|
||||||
'id',
|
'id',
|
||||||
@@ -485,6 +629,7 @@ export const openApiSpec = {
|
|||||||
'departureSimTime',
|
'departureSimTime',
|
||||||
'lat',
|
'lat',
|
||||||
'lon',
|
'lon',
|
||||||
|
'queue',
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
PackageState: {
|
PackageState: {
|
||||||
@@ -498,10 +643,12 @@ export const openApiSpec = {
|
|||||||
reward: { type: 'number' },
|
reward: { type: 'number' },
|
||||||
cargoType: { type: 'string' },
|
cargoType: { type: 'string' },
|
||||||
cargoCount: { type: 'integer' },
|
cargoCount: { type: 'integer' },
|
||||||
|
weightKg: { type: 'number', description: 'Package weight in kg (v0.27.0) — drives load validation and the per-kg payout part.' },
|
||||||
deadlineSimTime: { type: 'integer', description: 'Sim-clock epoch ms (game time)' },
|
deadlineSimTime: { type: 'integer', description: 'Sim-clock epoch ms (game time)' },
|
||||||
// 'expired' = an open OR loaded package whose deadline passed on a tick;
|
// 'expired' = an open OR loaded package whose deadline passed on a tick;
|
||||||
// loaded expired packages keep their slot, deliver no reward, abandon free.
|
// loaded expired packages keep their slot, deliver no reward, abandon free.
|
||||||
status: { enum: ['open', 'loaded', 'delivered', 'expired', 'abandoned'] },
|
// 'ignored' (v0.29.0, ISS-047 part B) = a dismissed open job — terminal, leaves the market.
|
||||||
|
status: { enum: ['open', 'loaded', 'delivered', 'expired', 'abandoned', 'ignored'] },
|
||||||
planeId: { type: ['string', 'null'] },
|
planeId: { type: ['string', 'null'] },
|
||||||
createdSimTime: { type: 'integer' },
|
createdSimTime: { type: 'integer' },
|
||||||
},
|
},
|
||||||
@@ -514,6 +661,7 @@ export const openApiSpec = {
|
|||||||
'reward',
|
'reward',
|
||||||
'cargoType',
|
'cargoType',
|
||||||
'cargoCount',
|
'cargoCount',
|
||||||
|
'weightKg', // v0.27.0 (ISS-045) — package weight in kg
|
||||||
'deadlineSimTime',
|
'deadlineSimTime',
|
||||||
'status',
|
'status',
|
||||||
'planeId',
|
'planeId',
|
||||||
|
|||||||
+165
-2
@@ -9,7 +9,7 @@ import { loadAirportsGeoJson } from '@/lib/airports';
|
|||||||
import { haversineKm } from '@/lib/geo';
|
import { haversineKm } from '@/lib/geo';
|
||||||
import { PLANE_TYPES } from '@/lib/game/catalog';
|
import { PLANE_TYPES } from '@/lib/game/catalog';
|
||||||
import { MARKET_TARGET_OPEN_PACKAGES, mulberry32 } from '@/lib/game/seed';
|
import { MARKET_TARGET_OPEN_PACKAGES, mulberry32 } from '@/lib/game/seed';
|
||||||
import { arrivalTimeFor } from './movement';
|
import { arrivalTimeFor, fuelAtWeighted, requiredFuelFor } from './movement';
|
||||||
import {
|
import {
|
||||||
clampTimeScale,
|
clampTimeScale,
|
||||||
deliverPackages,
|
deliverPackages,
|
||||||
@@ -105,6 +105,7 @@ describe('expirePackages', () => {
|
|||||||
{ id: 'p-loaded-past', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: clock - 1, status: 'loaded', planeId: 'plane-starter', createdSimTime: T0 },
|
{ id: 'p-loaded-past', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: clock - 1, status: 'loaded', planeId: 'plane-starter', createdSimTime: T0 },
|
||||||
{ id: 'p-delivered-past', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: clock - 1, status: 'delivered', planeId: null, createdSimTime: T0 },
|
{ id: 'p-delivered-past', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: clock - 1, status: 'delivered', planeId: null, createdSimTime: T0 },
|
||||||
{ id: 'p-abandoned-past', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: clock - 1, status: 'abandoned', planeId: null, createdSimTime: T0 },
|
{ id: 'p-abandoned-past', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: clock - 1, status: 'abandoned', planeId: null, createdSimTime: T0 },
|
||||||
|
{ id: 'p-ignored-past', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: clock - 1, status: 'ignored', planeId: null, createdSimTime: T0 },
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const n = await expirePackages(inst, clock);
|
const n = await expirePackages(inst, clock);
|
||||||
@@ -116,6 +117,7 @@ describe('expirePackages', () => {
|
|||||||
expect(byId.get('p-loaded-past')).toBe('expired'); // v0.12.0: loaded packages expire too (keep their slot)
|
expect(byId.get('p-loaded-past')).toBe('expired'); // v0.12.0: loaded packages expire too (keep their slot)
|
||||||
expect(byId.get('p-delivered-past')).toBe('delivered'); // terminal — never flips
|
expect(byId.get('p-delivered-past')).toBe('delivered'); // terminal — never flips
|
||||||
expect(byId.get('p-abandoned-past')).toBe('abandoned'); // terminal — never flips
|
expect(byId.get('p-abandoned-past')).toBe('abandoned'); // terminal — never flips
|
||||||
|
expect(byId.get('p-ignored-past')).toBe('ignored'); // v0.29.0 (ISS-047 part B) — terminal, never flips
|
||||||
});
|
});
|
||||||
|
|
||||||
it('a deadline exactly at the clock counts as expired', async () => {
|
it('a deadline exactly at the clock counts as expired', async () => {
|
||||||
@@ -182,7 +184,8 @@ describe('deliverPackages (v0.12.0 arrival delivery)', () => {
|
|||||||
expect(plane.locationIcao).toBe(TO);
|
expect(plane.locationIcao).toBe(TO);
|
||||||
expect(plane.lat).toBe(to.lat);
|
expect(plane.lat).toBe(to.lat);
|
||||||
expect(plane.lon).toBe(to.lon);
|
expect(plane.lon).toBe(to.lon);
|
||||||
expect(plane.fuel).toBeCloseTo(Math.max(0, type.maxFuel - type.burnPerKm * km), 6); // remaining fuel
|
// Remaining fuel per the v0.16.0 weight-proportional burn model (closed form).
|
||||||
|
expect(plane.fuel).toBeCloseTo(fuelAtWeighted(type.maxFuel, type.burnPerKm, type.emptyWeightKg, type.maxFuel, km, 1), 6);
|
||||||
expect(plane.departureSimTime).toBeNull();
|
expect(plane.departureSimTime).toBeNull();
|
||||||
expect(plane.destIcao).toBeNull(); // flight context cleared on landing
|
expect(plane.destIcao).toBeNull(); // flight context cleared on landing
|
||||||
|
|
||||||
@@ -234,6 +237,166 @@ describe('deliverPackages (v0.12.0 arrival delivery)', () => {
|
|||||||
.set({ status: 'flying', departureSimTime: T0 });
|
.set({ status: 'flying', departureSimTime: T0 });
|
||||||
expect(await deliverPackages(inst, T0 + 3_600_000)).toBe(0);
|
expect(await deliverPackages(inst, T0 + 3_600_000)).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// --- Auto-chain on landing (v0.25.0, ISS-043) ---
|
||||||
|
|
||||||
|
it('auto-chains to the next queued leg when fuel covers it', async () => {
|
||||||
|
const { inst, to, km, type } = await setupFlight('chain-ok.db'); // full tank EDDF→LEMD
|
||||||
|
const fc = await loadAirportsGeoJson();
|
||||||
|
const nextP = fc.features.find((f) => f.properties.icao === 'EHAM')!.properties;
|
||||||
|
const nextKm = haversineKm(to.lat, to.lon, nextP.lat, nextP.lon);
|
||||||
|
|
||||||
|
// Precondition sanity: a full-tank departure leaves enough for the LEMD→EHAM hop.
|
||||||
|
const landedFuel = fuelAtWeighted(type.maxFuel, type.burnPerKm, type.emptyWeightKg, type.maxFuel, km, 1);
|
||||||
|
expect(requiredFuelFor(type.burnPerKm, type.emptyWeightKg, type.maxFuel, nextKm)).toBeLessThanOrEqual(landedFuel);
|
||||||
|
|
||||||
|
await inst.db.update(schema.planes)
|
||||||
|
.set({ queue: JSON.stringify(['EHAM', 'EDDV']) })
|
||||||
|
.where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
|
const clock = T0 + travelMs(km, type.speedKmh); // exactly at arrival
|
||||||
|
expect(await deliverPackages(inst, clock)).toBe(1);
|
||||||
|
|
||||||
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
|
expect(plane.status).toBe('flying'); // chained — still airborne, no ground stop
|
||||||
|
expect(plane.destIcao).toBe('EHAM'); // first queued leg is now the active one
|
||||||
|
expect(plane.departureSimTime).toBe(clock); // departed at the arrival instant…
|
||||||
|
expect(plane.locationIcao).toBe(TO); // …from the airport just landed at
|
||||||
|
expect(plane.lat).toBe(to.lat);
|
||||||
|
expect(plane.lon).toBe(to.lon);
|
||||||
|
expect(JSON.parse(plane.queue)).toEqual(['EDDV']); // first leg consumed, rest kept in order
|
||||||
|
});
|
||||||
|
|
||||||
|
it('grounds when fuel cannot cover the next queued leg, keeping the queue intact', async () => {
|
||||||
|
const { inst, km, type } = await setupFlight('chain-nofuel.db');
|
||||||
|
const fc = await loadAirportsGeoJson();
|
||||||
|
const nextP = fc.features.find((f) => f.properties.icao === 'EHAM')!.properties;
|
||||||
|
|
||||||
|
// Depart with exactly the fuel for EDDF→LEMD → lands empty, cannot start LEMD→EHAM.
|
||||||
|
await inst.db.update(schema.planes)
|
||||||
|
.set({
|
||||||
|
fuel: requiredFuelFor(type.burnPerKm, type.emptyWeightKg, type.maxFuel, km),
|
||||||
|
queue: JSON.stringify(['EHAM']),
|
||||||
|
})
|
||||||
|
.where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
|
const clock = T0 + travelMs(km, type.speedKmh); // exactly at arrival
|
||||||
|
expect(await deliverPackages(inst, clock)).toBe(1);
|
||||||
|
|
||||||
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
|
expect(plane.status).toBe('available'); // grounded safely…
|
||||||
|
expect(plane.destIcao).toBeNull();
|
||||||
|
expect(plane.departureSimTime).toBeNull();
|
||||||
|
expect(JSON.parse(plane.queue)).toEqual(['EHAM']); // …queue kept for refuel + re-dispatch
|
||||||
|
});
|
||||||
|
|
||||||
|
it('grounds as before when the queue is empty', async () => {
|
||||||
|
const { inst, km } = await setupFlight('chain-empty.db'); // seeded default queue '[]'
|
||||||
|
|
||||||
|
expect(await deliverPackages(inst, T0 + travelMs(km, PLANE_TYPES.atr72.speedKmh))).toBe(1);
|
||||||
|
|
||||||
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
|
expect(plane.status).toBe('available'); // unchanged landing behavior…
|
||||||
|
expect(JSON.parse(plane.queue)).toEqual([]); // …and the queue stays empty
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('slow to 1× when a landing leaves any plane on the ground (ISS-057)', () => {
|
||||||
|
const FROM = 'EDDF';
|
||||||
|
const TO = 'LEMD';
|
||||||
|
|
||||||
|
// Starter flying EDDF→LEMD with departureSimTime set so its arrival is EXACTLY T0 —
|
||||||
|
// any advancing tick past T0 finalizes it. timeScale is the value under test;
|
||||||
|
// lastSelectedTimeScale mirrors what a manual POST /api/sim would have stored.
|
||||||
|
async function setupLanding(name: string, timeScale: number) {
|
||||||
|
const inst = await freshDb(name);
|
||||||
|
const fc = await loadAirportsGeoJson();
|
||||||
|
const from = fc.features.find((f) => f.properties.icao === FROM)!.properties;
|
||||||
|
const to = fc.features.find((f) => f.properties.icao === TO)!.properties;
|
||||||
|
const km = haversineKm(from.lat, from.lon, to.lat, to.lon);
|
||||||
|
const type = PLANE_TYPES.atr72;
|
||||||
|
|
||||||
|
await inst.db.update(schema.simState).set({ timeScale, lastSelectedTimeScale: timeScale });
|
||||||
|
await inst.db.update(schema.planes)
|
||||||
|
.set({ status: 'flying', destIcao: TO, departureSimTime: T0 - travelMs(km, type.speedKmh), fuel: type.maxFuel })
|
||||||
|
.where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
|
return { inst, from, km, type };
|
||||||
|
}
|
||||||
|
|
||||||
|
it('last plane lands → sim slows to 1× WITHOUT pausing; lastSelectedTimeScale is preserved', async () => {
|
||||||
|
const { inst } = await setupLanding('slow-last.db', 1000);
|
||||||
|
vi.setSystemTime(T0 + 2_000); // one full clamped tick at scale 1000 → clock T0+2e6 ≥ arrival (T0)
|
||||||
|
|
||||||
|
const sim = await tickOnce(inst);
|
||||||
|
|
||||||
|
expect(sim.paused).toBe(false); // no pause anymore — ISS-057 replaces it with a slow-down…
|
||||||
|
expect((await inst.db.select().from(schema.simState))[0].paused).toBe(false); // …persisted on the row…
|
||||||
|
expect(sim.timeScale).toBe(1); // …slowed to the floor…
|
||||||
|
expect(sim.lastSelectedTimeScale).toBe(1000); // …with the last manual speed kept for resume
|
||||||
|
expect((await inst.db.select().from(schema.planes))[0].status).toBe('available'); // landing itself unchanged
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a landing while another plane is still flying → slows to 1× (any plane on ground)', async () => {
|
||||||
|
const { inst, from, type } = await setupLanding('slow-other.db', 1000);
|
||||||
|
// A second plane on the same route departing at T0 — arrives far after this tick's clock.
|
||||||
|
await inst.db.insert(schema.planes).values({
|
||||||
|
id: 'p-b', model: 'atr72', status: 'flying', fuel: type.maxFuel, maxFuel: type.maxFuel,
|
||||||
|
locationIcao: FROM, destIcao: TO, lat: from.lat, lon: from.lon, departureSimTime: T0,
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.setSystemTime(T0 + 2_000);
|
||||||
|
const sim = await tickOnce(inst);
|
||||||
|
|
||||||
|
expect(sim.paused).toBe(false);
|
||||||
|
expect(sim.timeScale).toBe(1); // the just-landed starter is on ground → slow (literal issue reading)
|
||||||
|
const byId = new Map((await inst.db.select().from(schema.planes)).map((p) => [p.id, p.status]));
|
||||||
|
expect(byId.get('plane-starter')).toBe('available'); // the starter did land…
|
||||||
|
expect(byId.get('p-b')).toBe('flying'); // …but the fleet is not idle — still slowed
|
||||||
|
});
|
||||||
|
|
||||||
|
it('already at 1× → stays 1 (no-op slow)', async () => {
|
||||||
|
const { inst } = await setupLanding('slow-one.db', 1);
|
||||||
|
vi.setSystemTime(T0 + 2_000); // one tick at scale 1 advances 2e3 game ms — past the T0 arrival
|
||||||
|
|
||||||
|
const sim = await tickOnce(inst);
|
||||||
|
|
||||||
|
expect(sim.paused).toBe(false);
|
||||||
|
expect(sim.timeScale).toBe(1);
|
||||||
|
expect((await inst.db.select().from(schema.planes))[0].status).toBe('available');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a chained plane does NOT slow the sim (nothing is grounded)', async () => {
|
||||||
|
const { inst } = await setupLanding('slow-chain.db', 1000); // full tank, arrival exactly T0
|
||||||
|
// A queued next hop with plenty of fuel → chains on landing instead of grounding.
|
||||||
|
await inst.db.update(schema.planes)
|
||||||
|
.set({ queue: JSON.stringify(['EDDV']) })
|
||||||
|
.where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
|
vi.setSystemTime(T0 + 2_000); // one full clamped tick at scale 1000 → clock T0+2e6 ≥ arrival (T0)
|
||||||
|
const sim = await tickOnce(inst);
|
||||||
|
|
||||||
|
expect(sim.paused).toBe(false);
|
||||||
|
expect(sim.timeScale).toBe(1000); // still flying after the chain, nothing grounded — no slow…
|
||||||
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
|
expect(plane.status).toBe('flying'); // …the fresh select in tickOnce counts it as airborne
|
||||||
|
expect(plane.destIcao).toBe('EDDV');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('manually-paused sim is untouched by ticks (no landing processed while paused)', async () => {
|
||||||
|
const inst = await freshDb('slow-paused.db');
|
||||||
|
// The fleet is fully grounded (the seeded starter) — a paused tick must not touch the
|
||||||
|
// controls even though "any plane on ground" holds: the trigger requires a landing this tick.
|
||||||
|
await inst.db.update(schema.simState).set({ timeScale: 1000, lastSelectedTimeScale: 1000, paused: true });
|
||||||
|
|
||||||
|
vi.setSystemTime(T0 + 5_000);
|
||||||
|
const sim = await tickOnce(inst);
|
||||||
|
|
||||||
|
expect(sim.paused).toBe(true); // no landing processed while paused → trigger never fires
|
||||||
|
expect(sim.timeScale).toBe(1000);
|
||||||
|
expect(sim.lastSelectedTimeScale).toBe(1000);
|
||||||
|
expect((await inst.db.select().from(schema.planes))[0].status).toBe('available');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('spawnOpenPackages', () => {
|
describe('spawnOpenPackages', () => {
|
||||||
|
|||||||
+89
-25
@@ -5,6 +5,7 @@ import * as schema from '@/lib/db/schema';
|
|||||||
import { loadAirportsGeoJson } from '@/lib/airports';
|
import { loadAirportsGeoJson } from '@/lib/airports';
|
||||||
import { haversineKm } from '@/lib/geo';
|
import { haversineKm } from '@/lib/geo';
|
||||||
import { PLANE_TYPES } from '@/lib/game/catalog';
|
import { PLANE_TYPES } from '@/lib/game/catalog';
|
||||||
|
import { parseIcaoQueue } from '@/lib/game/state';
|
||||||
import {
|
import {
|
||||||
generatePackage,
|
generatePackage,
|
||||||
MARKET_TARGET_OPEN_PACKAGES,
|
MARKET_TARGET_OPEN_PACKAGES,
|
||||||
@@ -12,7 +13,7 @@ import {
|
|||||||
type Rng,
|
type Rng,
|
||||||
type SeedAirport,
|
type SeedAirport,
|
||||||
} from '@/lib/game/seed';
|
} from '@/lib/game/seed';
|
||||||
import { arrivalTimeFor, fuelAt } from './movement';
|
import { arrivalTimeFor, fuelAtWeighted, requiredFuelFor } from './movement';
|
||||||
|
|
||||||
// Server-authoritative sim engine (v0.7.0) — tick-on-read: there is NO background
|
// Server-authoritative sim engine (v0.7.0) — tick-on-read: there is NO background
|
||||||
// timer. Every read/action endpoint calls tickNow() first; the clock advances by
|
// timer. Every read/action endpoint calls tickNow() first; the clock advances by
|
||||||
@@ -71,17 +72,36 @@ export async function tickOnce(inst: GameDb): Promise<schema.SimStateRow> {
|
|||||||
const advanceMs = sim.paused ? 0 : Math.min(elapsed, MAX_TICK_ELAPSED_MS) * sim.timeScale;
|
const advanceMs = sim.paused ? 0 : Math.min(elapsed, MAX_TICK_ELAPSED_MS) * sim.timeScale;
|
||||||
const clockMs = Math.round(sim.clockMs + advanceMs);
|
const clockMs = Math.round(sim.clockMs + advanceMs);
|
||||||
|
|
||||||
|
let landedThisTick = 0;
|
||||||
if (advanceMs > 0) {
|
if (advanceMs > 0) {
|
||||||
await expirePackages(inst, clockMs);
|
await expirePackages(inst, clockMs);
|
||||||
await deliverPackages(inst, clockMs);
|
// ISS-057: remember the landings so the tick can slow down when a plane is left on ground.
|
||||||
|
landedThisTick = await deliverPackages(inst, clockMs);
|
||||||
await spawnOpenPackages(inst, clockMs);
|
await spawnOpenPackages(inst, clockMs);
|
||||||
// AFTER delivery on purpose: a plane that just landed gets work spawned
|
// AFTER delivery on purpose: a plane that just landed gets work spawned
|
||||||
// at its new location within the same tick.
|
// at its new location within the same tick.
|
||||||
await spawnCoveragePackages(inst, clockMs);
|
await spawnCoveragePackages(inst, clockMs);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const sets: Partial<Pick<schema.SimStateRow, 'clockMs' | 'lastRealTickMs' | 'timeScale'>> = {
|
||||||
|
clockMs,
|
||||||
|
lastRealTickMs: nowMs,
|
||||||
|
};
|
||||||
|
// Slow on landing (ISS-057): when ≥1 plane landed this tick and ANY plane is grounded
|
||||||
|
// ('available') afterwards, drop the sim to MIN_TIME_SCALE — a just-landed plane counts, so
|
||||||
|
// any real landing slows. A chained plane stays 'flying' via deliverPackages' auto-chain
|
||||||
|
// branch, so a pure-chain tick with nothing grounded does NOT slow. Pause is manual-only now;
|
||||||
|
// flyPlane restores lastSelectedTimeScale when the last grounded plane takes off. Arrival-
|
||||||
|
// triggered by design: a grounded fleet at high scale is left alone (no idle-enforcement), and
|
||||||
|
// a paused tick never processes landings (advanceMs === 0), so the trigger only fires on an
|
||||||
|
// advancing tick — a manual speed change while planes sit grounded survives until the next landing.
|
||||||
|
if (landedThisTick > 0) {
|
||||||
|
const available = await inst.db.select().from(schema.planes).where(eq(schema.planes.status, 'available'));
|
||||||
|
if (available.length >= 1) sets.timeScale = MIN_TIME_SCALE;
|
||||||
|
}
|
||||||
|
|
||||||
// Persist lastRealTickMs even when nothing advanced — it is the tick anchor.
|
// Persist lastRealTickMs even when nothing advanced — it is the tick anchor.
|
||||||
await inst.db.update(schema.simState).set({ clockMs, lastRealTickMs: nowMs });
|
await inst.db.update(schema.simState).set(sets);
|
||||||
await persist(inst);
|
await persist(inst);
|
||||||
const updated = (await inst.db.select().from(schema.simState))[0];
|
const updated = (await inst.db.select().from(schema.simState))[0];
|
||||||
if (!updated) throw new Error('sim_state row missing after tick');
|
if (!updated) throw new Error('sim_state row missing after tick');
|
||||||
@@ -105,12 +125,17 @@ export async function expirePackages(inst: GameDb, clockMs: number): Promise<num
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Finalize in-flight planes whose arrival time has passed (v0.12.0 delivery):
|
// Finalize in-flight planes whose arrival time has passed (v0.12.0 delivery):
|
||||||
// ground the plane at its dest_icao with its remaining fuel, then for every
|
// for every package bound to the plane and destined for its dest_icao — 'loaded'
|
||||||
// package bound to it and destined for that airport — 'loaded' ones still inside
|
// ones still inside their deadline are delivered (cash += reward + reputation
|
||||||
// their deadline are delivered (cash += reward + reputation gain per package),
|
// gain per package), 'expired' ones just unbind (no reward). Packages destined
|
||||||
// 'expired' ones just unbind (no reward). Packages destined elsewhere stay loaded
|
// elsewhere stay loaded on the plane for a later leg. Then (v0.25.0, ISS-043)
|
||||||
// on the plane for a later leg. Idempotent — a finalized plane leaves the
|
// auto-chain: if the queue holds legs and fuel covers the first one, start it
|
||||||
// 'flying' state, so it can never be awarded twice. Returns planes landed.
|
// immediately from the arrival airport; otherwise ground the plane there with
|
||||||
|
// its remaining fuel (a short tank keeps the queue intact for refuel + re-dispatch).
|
||||||
|
// Idempotent — a finalized plane either leaves the 'flying' state or starts a NEW
|
||||||
|
// leg whose own arrival is in the future, so it can never be awarded twice.
|
||||||
|
// Returns planes landed. NOTE: runs BEFORE tickOnce's slow-down check on purpose —
|
||||||
|
// a chained plane is already 'flying' again here, so a pure-chain landing never slows the sim.
|
||||||
export async function deliverPackages(inst: GameDb, clockMs: number): Promise<number> {
|
export async function deliverPackages(inst: GameDb, clockMs: number): Promise<number> {
|
||||||
const [planeRows, packageRows] = await Promise.all([
|
const [planeRows, packageRows] = await Promise.all([
|
||||||
inst.db.select().from(schema.planes),
|
inst.db.select().from(schema.planes),
|
||||||
@@ -131,20 +156,11 @@ export async function deliverPackages(inst: GameDb, clockMs: number): Promise<nu
|
|||||||
const distanceKm = haversineKm(from.lat, from.lon, to.lat, to.lon);
|
const distanceKm = haversineKm(from.lat, from.lon, to.lat, to.lon);
|
||||||
if (clockMs < arrivalTimeFor(p.departureSimTime, distanceKm, type.speedKmh)) continue;
|
if (clockMs < arrivalTimeFor(p.departureSimTime, distanceKm, type.speedKmh)) continue;
|
||||||
|
|
||||||
// Arrived: progress is exactly 1 here, so remaining fuel is the full-leg burn.
|
// Arrived: progress is exactly 1 here, so remaining fuel is the full-leg weighted burn.
|
||||||
await inst.db.update(schema.planes)
|
const landedFuel = fuelAtWeighted(p.fuel, type.burnPerKm, type.emptyWeightKg, type.maxFuel, distanceKm, 1);
|
||||||
.set({
|
|
||||||
status: 'available',
|
|
||||||
locationIcao: to.icao,
|
|
||||||
lat: to.lat,
|
|
||||||
lon: to.lon,
|
|
||||||
fuel: fuelAt(p.fuel, type.burnPerKm, distanceKm, 1),
|
|
||||||
departureSimTime: null,
|
|
||||||
destIcao: null,
|
|
||||||
})
|
|
||||||
.where(eq(schema.planes.id, p.id));
|
|
||||||
|
|
||||||
// Deliver every bound package whose destination is the airport just reached.
|
// Deliver every bound package whose destination is the airport just reached —
|
||||||
|
// runs whether or not a queued leg chains next (ISS-043).
|
||||||
const onBoard = packageRows.filter((pk) => pk.planeId === p.id && pk.destIcao === to.icao);
|
const onBoard = packageRows.filter((pk) => pk.planeId === p.id && pk.destIcao === to.icao);
|
||||||
for (const pk of onBoard) {
|
for (const pk of onBoard) {
|
||||||
if (pk.status === 'loaded' && clockMs <= pk.deadlineSimTime) {
|
if (pk.status === 'loaded' && clockMs <= pk.deadlineSimTime) {
|
||||||
@@ -161,6 +177,47 @@ export async function deliverPackages(inst: GameDb, clockMs: number): Promise<nu
|
|||||||
await inst.db.update(schema.packages).set({ planeId: null }).where(eq(schema.packages.id, pk.id));
|
await inst.db.update(schema.packages).set({ planeId: null }).where(eq(schema.packages.id, pk.id));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Auto-chain (ISS-043): with a non-empty queue and enough fuel for the first
|
||||||
|
// queued leg, start it immediately from `to` — same feasibility rule as flyPlane
|
||||||
|
// (requiredFuelFor is independent of current load). Otherwise ground here; an
|
||||||
|
// unknown ICAO in the queue simply cannot chain. The remaining queue is kept
|
||||||
|
// intact either way so a grounded plane can refuel and re-dispatch.
|
||||||
|
const queue = parseIcaoQueue(p.queue);
|
||||||
|
let chainedTo: string | null = null;
|
||||||
|
if (queue.length > 0) {
|
||||||
|
const nextDest = queue[0];
|
||||||
|
const next = byIcao.get(nextDest); // unknown ICAO in the queue → cannot chain
|
||||||
|
if (next && requiredFuelFor(type.burnPerKm, type.emptyWeightKg, type.maxFuel, haversineKm(to.lat, to.lon, next.lat, next.lon)) <= landedFuel) {
|
||||||
|
queue.shift();
|
||||||
|
chainedTo = nextDest;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await inst.db.update(schema.planes)
|
||||||
|
.set(
|
||||||
|
chainedTo
|
||||||
|
? {
|
||||||
|
status: 'flying',
|
||||||
|
locationIcao: to.icao,
|
||||||
|
lat: to.lat,
|
||||||
|
lon: to.lon,
|
||||||
|
fuel: landedFuel,
|
||||||
|
destIcao: chainedTo,
|
||||||
|
departureSimTime: clockMs, // the arrival instant — position is exactly `to`
|
||||||
|
queue: JSON.stringify(queue),
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
status: 'available',
|
||||||
|
locationIcao: to.icao,
|
||||||
|
lat: to.lat,
|
||||||
|
lon: to.lon,
|
||||||
|
fuel: landedFuel,
|
||||||
|
departureSimTime: null,
|
||||||
|
destIcao: null,
|
||||||
|
queue: JSON.stringify(queue),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.where(eq(schema.planes.id, p.id));
|
||||||
n++;
|
n++;
|
||||||
}
|
}
|
||||||
return n;
|
return n;
|
||||||
@@ -265,13 +322,20 @@ export function runAction<T>(fn: (inst: GameDb) => Promise<T>): Promise<T> {
|
|||||||
|
|
||||||
// Tick first so the returned state reflects current time, then apply the new
|
// Tick first so the returned state reflects current time, then apply the new
|
||||||
// controls. timeScale is clamped to [1, 1000]; validation of raw input happens in
|
// controls. timeScale is clamped to [1, 1000]; validation of raw input happens in
|
||||||
// the route handler (400 on non-number / non-boolean).
|
// the route handler (400 on non-number / non-boolean). ISS-057: posting a timeScale
|
||||||
|
// ALSO records it as lastSelectedTimeScale — the resume target flyPlane restores when
|
||||||
|
// the last grounded plane takes off. A {paused}-only post never touches it, so the
|
||||||
|
// last manual intent wins without an extra flag.
|
||||||
export function applyTimeControls(input: SimControlsInput): Promise<schema.SimStateRow> {
|
export function applyTimeControls(input: SimControlsInput): Promise<schema.SimStateRow> {
|
||||||
return withLock(async () => {
|
return withLock(async () => {
|
||||||
const inst = await getGameDb();
|
const inst = await getGameDb();
|
||||||
await tickOnce(inst);
|
await tickOnce(inst);
|
||||||
const sets: Partial<Pick<schema.SimStateRow, 'timeScale' | 'paused'>> = {};
|
const sets: Partial<Pick<schema.SimStateRow, 'timeScale' | 'lastSelectedTimeScale' | 'paused'>> = {};
|
||||||
if (input.timeScale !== undefined) sets.timeScale = clampTimeScale(input.timeScale);
|
if (input.timeScale !== undefined) {
|
||||||
|
const scale = clampTimeScale(input.timeScale);
|
||||||
|
sets.timeScale = scale;
|
||||||
|
sets.lastSelectedTimeScale = scale;
|
||||||
|
}
|
||||||
if (input.paused !== undefined) sets.paused = input.paused;
|
if (input.paused !== undefined) sets.paused = input.paused;
|
||||||
if (Object.keys(sets).length > 0) await inst.db.update(schema.simState).set(sets);
|
if (Object.keys(sets).length > 0) await inst.db.update(schema.simState).set(sets);
|
||||||
await persist(inst);
|
await persist(inst);
|
||||||
|
|||||||
+80
-14
@@ -1,12 +1,24 @@
|
|||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import { haversineKm } from '@/lib/geo';
|
import { haversineKm } from '@/lib/geo';
|
||||||
import { arrivalTimeFor, fuelAt, positionAt, progressAt, travelDurationMs } from './movement';
|
import {
|
||||||
|
arrivalTimeFor,
|
||||||
|
burnRateConstant,
|
||||||
|
FUEL_DENSITY_KG_PER_L,
|
||||||
|
fuelAtWeighted,
|
||||||
|
maxRangeKm,
|
||||||
|
positionAt,
|
||||||
|
progressAt,
|
||||||
|
requiredFuelFor,
|
||||||
|
travelDurationMs,
|
||||||
|
} from './movement';
|
||||||
|
|
||||||
// Synthetic in-flight fixtures — no DB needed: everything is a pure function of
|
// Synthetic in-flight fixtures — no DB needed: everything is a pure function of
|
||||||
// the sim clock. ATR 72-600 numbers from lib/game/catalog.ts.
|
// the sim clock. ATR 72-600 numbers from lib/game/catalog.ts.
|
||||||
const DEP = 1_750_000_000_000; // departure sim time (ms)
|
const DEP = 1_750_000_000_000; // departure sim time (ms)
|
||||||
const SPEED = 510; // km/h
|
const SPEED = 510; // km/h
|
||||||
const BURN = 1.75; // L/km
|
const BURN = 1.75; // L/km at a full tank
|
||||||
|
const WE = 9_300; // kg, operating empty weight
|
||||||
|
const TANK = 6_300; // liters, full tank
|
||||||
|
|
||||||
// Frankfurt → Madrid, real coordinates from the CSV dataset.
|
// Frankfurt → Madrid, real coordinates from the CSV dataset.
|
||||||
const FROM = { lat: 50.0333, lon: 8.5706 };
|
const FROM = { lat: 50.0333, lon: 8.5706 };
|
||||||
@@ -96,17 +108,53 @@ describe('positionAt (great-circle slerp)', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('fuelAt', () => {
|
describe('weighted burn model (v0.16.0)', () => {
|
||||||
it('burns fuel proportionally to distance flown', () => {
|
it('calibrates so a full tank burns exactly the old constant rate', () => {
|
||||||
const start = 6_300; // full ATR tank
|
const k = burnRateConstant(BURN, WE, TANK);
|
||||||
expect(fuelAt(start, BURN, KM, 0)).toBe(start);
|
expect(k * (WE + FUEL_DENSITY_KG_PER_L * TANK)).toBeCloseTo(BURN, 12);
|
||||||
expect(fuelAt(start, BURN, KM, 0.5)).toBeCloseTo(start - BURN * KM / 2, 9);
|
|
||||||
expect(fuelAt(start, BURN, KM, 1)).toBeCloseTo(start - BURN * KM, 9);
|
// Over a short hop from full, weighted ≈ constant — divergence only grows as fuel drops off.
|
||||||
|
const d = 100;
|
||||||
|
const consumed = TANK - fuelAtWeighted(TANK, BURN, WE, TANK, d, 1);
|
||||||
|
expect(Math.abs(consumed - BURN * d)).toBeLessThan(1); // < 1 L over 100 km from full
|
||||||
|
});
|
||||||
|
|
||||||
|
it('consumption matches numeric integration of r(F) = k·(We + ρF)', () => {
|
||||||
|
const k = burnRateConstant(BURN, WE, TANK);
|
||||||
|
const rho = FUEL_DENSITY_KG_PER_L;
|
||||||
|
// Euler-integrate dF/dx = −k(We + ρF) from a full tank over the whole leg.
|
||||||
|
const steps = 200_000;
|
||||||
|
const h = KM / steps;
|
||||||
|
let f = TANK;
|
||||||
|
for (let i = 0; i < steps; i++) f -= k * (WE + rho * f) * h;
|
||||||
|
expect(Math.abs(fuelAtWeighted(TANK, BURN, WE, TANK, KM, 1) - f)).toBeLessThan(0.001); // Euler drift is sub-milliliter here
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requiredFuelFor is zero for a zero leg and strictly increasing in distance', () => {
|
||||||
|
expect(requiredFuelFor(BURN, WE, TANK, 0)).toBe(0);
|
||||||
|
let prev = requiredFuelFor(BURN, WE, TANK, 100);
|
||||||
|
for (const d of [500, 1_000, 2_000, 3_000, 4_000]) {
|
||||||
|
const cur = requiredFuelFor(BURN, WE, TANK, d);
|
||||||
|
expect(cur).toBeGreaterThan(prev);
|
||||||
|
prev = cur;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a lighter start burns less over the same distance', () => {
|
||||||
|
const burnFromFull = TANK - fuelAtWeighted(TANK, BURN, WE, TANK, KM, 1);
|
||||||
|
const burnFromHalf = TANK / 2 - fuelAtWeighted(TANK / 2, BURN, WE, TANK, KM, 1);
|
||||||
|
expect(burnFromFull).toBeGreaterThan(burnFromHalf);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('starting with exactly the required fuel arrives on empty', () => {
|
||||||
|
const req = requiredFuelFor(BURN, WE, TANK, KM);
|
||||||
|
expect(fuelAtWeighted(req, BURN, WE, TANK, KM, 1)).toBeCloseTo(0, 6);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('clamps at zero instead of going negative', () => {
|
it('clamps at zero instead of going negative', () => {
|
||||||
expect(fuelAt(100, BURN, 1_000, 1)).toBe(0); // needs 1750 L, has 100
|
expect(fuelAtWeighted(100, BURN, WE, TANK, KM, 1)).toBe(0); // needs ~2800 L from full, has 100
|
||||||
expect(fuelAt(100, BURN, 1_000, 0.01)).toBeCloseTo(100 - 17.5, 9);
|
expect(fuelAtWeighted(TANK, BURN, WE, TANK, KM, 0)).toBe(TANK);
|
||||||
|
expect(fuelAtWeighted(TANK, BURN, WE, TANK, 0, 1)).toBe(TANK);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('composes with progressAt for a just-before-arrival snapshot', () => {
|
it('composes with progressAt for a just-before-arrival snapshot', () => {
|
||||||
@@ -114,9 +162,27 @@ describe('fuelAt', () => {
|
|||||||
const clock = DEP + duration - 1; // one ms before arrival
|
const clock = DEP + duration - 1; // one ms before arrival
|
||||||
const p = positionAt(FROM.lat, FROM.lon, TO.lat, TO.lon, progressAt(DEP, KM, SPEED, clock));
|
const p = positionAt(FROM.lat, FROM.lon, TO.lat, TO.lon, progressAt(DEP, KM, SPEED, clock));
|
||||||
expect(haversineKm(p.lat, p.lon, TO.lat, TO.lon)).toBeGreaterThan(0); // not yet at the gate
|
expect(haversineKm(p.lat, p.lon, TO.lat, TO.lon)).toBeGreaterThan(0); // not yet at the gate
|
||||||
expect(fuelAt(6_300, BURN, KM, progressAt(DEP, KM, SPEED, clock))).toBeCloseTo(
|
expect(fuelAtWeighted(TANK, BURN, WE, TANK, KM, progressAt(DEP, KM, SPEED, clock))).toBeGreaterThan(0);
|
||||||
6_300 - BURN * KM * (1 - 1 / duration),
|
});
|
||||||
6,
|
});
|
||||||
);
|
|
||||||
|
describe('maxRangeKm (v0.28.0)', () => {
|
||||||
|
it('ATR 72-600 full tank ≈ 4439 km (±5%)', () => {
|
||||||
|
const r = maxRangeKm(BURN, WE, TANK);
|
||||||
|
expect(r).toBeGreaterThan(4439 * 0.95);
|
||||||
|
expect(r).toBeLessThan(4439 * 1.05);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('increases with tank size and decreases with burn rate', () => {
|
||||||
|
expect(maxRangeKm(BURN, WE, TANK * 2)).toBeGreaterThan(maxRangeKm(BURN, WE, TANK));
|
||||||
|
expect(maxRangeKm(3, WE, TANK)).toBeLessThan(maxRangeKm(BURN, WE, TANK));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('zero fuel → zero range', () => {
|
||||||
|
expect(maxRangeKm(BURN, WE, 0)).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a non-positive empty weight', () => {
|
||||||
|
expect(() => maxRangeKm(BURN, 0, TANK)).toThrow();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+62
-4
@@ -65,8 +65,66 @@ export function positionAt(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fuel remaining after flying `progress` of a leg of distanceKm. Clamped at 0 —
|
// --- Weight-proportional fuel burn (v0.16.0) ---
|
||||||
// range exhaustion is not modeled yet (fuel management/refueling comes later).
|
//
|
||||||
export function fuelAt(startFuel: number, burnPerKm: number, distanceKm: number, progress: number): number {
|
// The instantaneous burn rate is proportional to total weight: r(F) = k·(We + ρF) L/km,
|
||||||
return Math.max(0, startFuel - burnPerKm * distanceKm * progress);
|
// where We is the empty weight in kg, ρ the fuel density and F the current load in
|
||||||
|
// liters — a heavier plane burns more per km. k is calibrated so that a FULL tank
|
||||||
|
// burns exactly the catalog's constant burnPerKm: k = burnPerKm / (We + ρ·maxFuel),
|
||||||
|
// so full-tank legs match the old model at departure and only diverge as fuel (and
|
||||||
|
// weight) drops off in flight. Closed forms of dF/dx = −k(We + ρF):
|
||||||
|
// fuel after distance D from F₀: (F₀ + We/ρ)·e^{−kρD} − We/ρ
|
||||||
|
// consumption over D: (F₀ + We/ρ)·(1 − e^{−kρD})
|
||||||
|
// fuel required to cover D arriving with 0, independent of F₀: (We/ρ)(e^{kρD} − 1)
|
||||||
|
|
||||||
|
// Jet-A1 density in kg/L — converts a liter load into its weight contribution.
|
||||||
|
export const FUEL_DENSITY_KG_PER_L = 0.8;
|
||||||
|
|
||||||
|
// Calibration constant k for one plane type (see the model note above).
|
||||||
|
export function burnRateConstant(burnPerKm: number, emptyWeightKg: number, maxFuel: number): number {
|
||||||
|
return burnPerKm / (emptyWeightKg + FUEL_DENSITY_KG_PER_L * maxFuel);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fuel remaining after flying `progress` of a leg of distanceKm from startFuel under the
|
||||||
|
// weighted model. Clamped at 0 — range exhaustion is not modeled (a plane that runs dry
|
||||||
|
// limps to the gate on fumes, same as before).
|
||||||
|
export function fuelAtWeighted(
|
||||||
|
startFuel: number,
|
||||||
|
burnPerKm: number,
|
||||||
|
emptyWeightKg: number,
|
||||||
|
maxFuel: number,
|
||||||
|
distanceKm: number,
|
||||||
|
progress: number,
|
||||||
|
): number {
|
||||||
|
const d = distanceKm * progress;
|
||||||
|
if (d <= 0) return startFuel;
|
||||||
|
const k = burnRateConstant(burnPerKm, emptyWeightKg, maxFuel);
|
||||||
|
const rho = FUEL_DENSITY_KG_PER_L;
|
||||||
|
const f = (startFuel + emptyWeightKg / rho) * Math.exp(-k * rho * d) - emptyWeightKg / rho;
|
||||||
|
return Math.max(0, f);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Total fuel required to cover distanceKm arriving with an empty tank — independent of the
|
||||||
|
// starting load. A leg is flyable from a plane iff its current fuel covers this amount; it
|
||||||
|
// fits in the aircraft at all iff this does not exceed the tank capacity.
|
||||||
|
export function requiredFuelFor(
|
||||||
|
burnPerKm: number,
|
||||||
|
emptyWeightKg: number,
|
||||||
|
maxFuel: number,
|
||||||
|
distanceKm: number,
|
||||||
|
): number {
|
||||||
|
if (distanceKm <= 0) return 0;
|
||||||
|
const k = burnRateConstant(burnPerKm, emptyWeightKg, maxFuel);
|
||||||
|
const rho = FUEL_DENSITY_KG_PER_L;
|
||||||
|
return (emptyWeightKg / rho) * (Math.exp(k * rho * distanceKm) - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Max range from a FULL tank under the weighted model — solve requiredFuelFor(d) = maxFuel for d:
|
||||||
|
// (We/ρ)(e^{kρd} − 1) = F → d = ln(1 + ρF/We) · (We + ρF)/(ρ·burnPerKm).
|
||||||
|
// Returns raw km (call sites round); zero fuel gives exactly 0. Pure — display-only, the sim
|
||||||
|
// itself does not model range exhaustion (see fuelAtWeighted).
|
||||||
|
export function maxRangeKm(burnPerKm: number, emptyWeightKg: number, maxFuel: number): number {
|
||||||
|
if (!(emptyWeightKg > 0)) throw new Error('emptyWeightKg must be > 0');
|
||||||
|
const rho = FUEL_DENSITY_KG_PER_L;
|
||||||
|
return Math.log(1 + (rho * maxFuel) / emptyWeightKg) * ((emptyWeightKg + rho * maxFuel) / (rho * burnPerKm));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useState } from 'react';
|
||||||
|
import type { StateSnapshot } from '@/lib/game/state';
|
||||||
|
|
||||||
|
// ISS-021 (v0.20.0) — shared action runner for the side panes (extracted verbatim from
|
||||||
|
// RightPane.runAction when the On board section moved to LeftPane). POSTs an action endpoint;
|
||||||
|
// every success returns the FULL post-action snapshot (v0.8.0 convention), pushed into the
|
||||||
|
// shared shell state immediately via applySnapshot so the UI updates without waiting for the
|
||||||
|
// next poll tick. A non-2xx {error} body becomes the pane's inline error AND is mirrored to
|
||||||
|
// the shell as a bottom-right toast via onError (ISS-008 — both surfaces by design). Buttons
|
||||||
|
// are disabled while a request is in flight, so at most one action runs per pane at a time.
|
||||||
|
export function useGameAction(
|
||||||
|
state: StateSnapshot | null,
|
||||||
|
applySnapshot: (snapshot: StateSnapshot) => void,
|
||||||
|
onError?: (message: string) => void,
|
||||||
|
): { runAction: (path: string, body?: unknown) => Promise<void>; busy: boolean; actionError: string | null } {
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
// Inline error from a failed action — auto-clears on the next successful poll (the shell's
|
||||||
|
// snapshot prop changes every tick) or the next successful action.
|
||||||
|
const [actionError, setActionError] = useState<string | null>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
if (state !== null) setActionError(null);
|
||||||
|
}, [state]);
|
||||||
|
|
||||||
|
const runAction = useCallback(
|
||||||
|
async (path: string, body?: unknown) => {
|
||||||
|
if (busy) return;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const res = await fetch(path, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: body === undefined ? undefined : JSON.stringify(body),
|
||||||
|
cache: 'no-store',
|
||||||
|
});
|
||||||
|
const data = (await res.json()) as StateSnapshot & { error?: string };
|
||||||
|
if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
|
||||||
|
setActionError(null);
|
||||||
|
applySnapshot(data);
|
||||||
|
} catch (err) {
|
||||||
|
const message = err instanceof Error ? err.message : String(err);
|
||||||
|
setActionError(message); // inline pane error stays…
|
||||||
|
onError?.(message); // …and the shell mirrors it as a bottom-right toast (ISS-008)
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[applySnapshot, busy, onError],
|
||||||
|
);
|
||||||
|
|
||||||
|
return { runAction, busy, actionError };
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { advanceSimClock, type SimClockAnchor } from './useSimClock';
|
||||||
|
|
||||||
|
// ISS-007 (v0.16.1) — the pure extrapolation core of lib/useSimClock.ts. The hook itself is a
|
||||||
|
// thin setInterval + re-sync wrapper covered by e2e (panes.spec.ts "ticks smoothly between polls");
|
||||||
|
// this suite pins the math: game time advances real-time × timeScale, frozen while paused.
|
||||||
|
|
||||||
|
const anchor = (over: Partial<SimClockAnchor> = {}): SimClockAnchor => ({
|
||||||
|
clockMs: 1_750_000_000_000,
|
||||||
|
at: 1_000_000,
|
||||||
|
timeScale: 1,
|
||||||
|
paused: false,
|
||||||
|
...over,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('advanceSimClock', () => {
|
||||||
|
it('advances by exactly elapsed real-time × timeScale while running', () => {
|
||||||
|
expect(advanceSimClock(anchor(), 1_001_000)).toBe(1_750_000_000_000 + 1_000); // scale 1: 1 s real = 1 s game
|
||||||
|
expect(advanceSimClock(anchor({ timeScale: 25 }), 1_002_500)).toBe(1_750_000_000_000 + 62_500);
|
||||||
|
// The e2e scenario: scale 1000, 2.5 s real → 2 500 game seconds.
|
||||||
|
expect(advanceSimClock(anchor({ timeScale: 1000 }), 1_002_500)).toBe(1_750_000_000_000 + 2_500_000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns the anchor value exactly at zero elapsed', () => {
|
||||||
|
expect(advanceSimClock(anchor({ timeScale: 1000 }), 1_000_000)).toBe(1_750_000_000_000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is frozen while paused regardless of elapsed or scale', () => {
|
||||||
|
const a = anchor({ timeScale: 1000, paused: true });
|
||||||
|
expect(advanceSimClock(a, 1_000_000)).toBe(1_750_000_000_000);
|
||||||
|
expect(advanceSimClock(a, 2_000_000)).toBe(1_750_000_000_000); // a full second later — still frozen
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clamps to the anchor value when nowMs is before the anchor (clock skew), never backwards', () => {
|
||||||
|
expect(advanceSimClock(anchor({ timeScale: 1000 }), 999_999)).toBe(1_750_000_000_000);
|
||||||
|
expect(advanceSimClock(anchor({ paused: true }), 999_999)).toBe(1_750_000_000_000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('mirrors the server tick model (tickOnce): advance = elapsed × timeScale while actively polled', () => {
|
||||||
|
// lib/sim/engine.ts: clockMs += min(now − lastRealTickMs, MAX_TICK_ELAPSED_MS) × timeScale.
|
||||||
|
// For gaps under the 2 s clamp the client extrapolation is exactly the server's own formula.
|
||||||
|
const scale = 50;
|
||||||
|
for (const gap of [1, 250, 999, 1_999]) {
|
||||||
|
expect(advanceSimClock(anchor({ timeScale: scale }), 1_000_000 + gap)).toBe(
|
||||||
|
1_750_000_000_000 + gap * scale,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
import type { StateSnapshot } from './game/state';
|
||||||
|
|
||||||
|
// ISS-007 (v0.16.1): the sim clock ticks smoothly on the CLIENT between polls instead of
|
||||||
|
// jumping once per snapshot. The server's authoritative rate is exactly real-time × timeScale
|
||||||
|
// (tickOnce in lib/sim/engine.ts: advance = min(elapsed, MAX_TICK_ELAPSED_MS) × timeScale), so
|
||||||
|
// client-side extrapolation mirrors the server's own model. Every new snapshot re-anchors to
|
||||||
|
// server truth, bounding any drift by network latency only.
|
||||||
|
|
||||||
|
export interface SimClockAnchor {
|
||||||
|
// Server truth at anchor time — the snapshot's simState.clockMs.
|
||||||
|
clockMs: number;
|
||||||
|
// Date.now() when that snapshot was received.
|
||||||
|
at: number;
|
||||||
|
timeScale: number;
|
||||||
|
paused: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pure core of the extrapolation — mirrors tickOnce: while running, game time advances by
|
||||||
|
// real-time × timeScale; while paused it is frozen (advance 0). nowMs before `at` clamps to
|
||||||
|
// the anchor value instead of going backwards. Unit-testable in node.
|
||||||
|
export function advanceSimClock(anchor: SimClockAnchor, nowMs: number): number {
|
||||||
|
if (anchor.paused) return anchor.clockMs;
|
||||||
|
return anchor.clockMs + Math.max(0, nowMs - anchor.at) * anchor.timeScale;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ~10 fps display refresh — smooth for a seconds-precision wall clock without busy re-renders.
|
||||||
|
const DISPLAY_TICK_MS = 100;
|
||||||
|
|
||||||
|
export interface SimClockControls {
|
||||||
|
// EFFECTIVE controls (optimistic pending scale / current pause), not the snapshot's:
|
||||||
|
// UI changes take effect on click/drag without waiting for a confirming snapshot.
|
||||||
|
timeScale: number;
|
||||||
|
paused: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Returns the display clockMs to render, or null until the first snapshot arrives.
|
||||||
|
export function useSimClock(snapshot: StateSnapshot | null, controls: SimClockControls): number | null {
|
||||||
|
const anchorRef = useRef<SimClockAnchor | null>(null);
|
||||||
|
const [displayMs, setDisplayMs] = useState<number | null>(null);
|
||||||
|
|
||||||
|
// Re-sync on every snapshot AND effective-control change: snap to server truth. The snapshot
|
||||||
|
// object is fresh per poll (useGameState), so this runs once per poll cycle as well.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!snapshot) return;
|
||||||
|
anchorRef.current = {
|
||||||
|
clockMs: snapshot.simState.clockMs,
|
||||||
|
at: Date.now(),
|
||||||
|
timeScale: controls.timeScale,
|
||||||
|
paused: controls.paused,
|
||||||
|
};
|
||||||
|
setDisplayMs(advanceSimClock(anchorRef.current, Date.now()));
|
||||||
|
}, [snapshot, controls.timeScale, controls.paused]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const id = setInterval(() => {
|
||||||
|
const anchor = anchorRef.current;
|
||||||
|
if (anchor) setDisplayMs(advanceSimClock(anchor, Date.now()));
|
||||||
|
}, DISPLAY_TICK_MS);
|
||||||
|
return () => clearInterval(id);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// First paint after a snapshot arrives happens before the re-sync effect runs — show the
|
||||||
|
// snapshot value directly so the clock never blanks for a frame.
|
||||||
|
return displayMs ?? (snapshot ? snapshot.simState.clockMs : null);
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { MAX_TOASTS, pushToast, type Toast } from './useToasts';
|
||||||
|
|
||||||
|
// ISS-008 (v0.17.0): the toast queue's pure core — append + cap at MAX_TOASTS dropping the
|
||||||
|
// oldest. The hook itself is a thin useState wrapper around this (auto-dismiss timers are
|
||||||
|
// plain setTimeout, covered by e2e via the visible toasts).
|
||||||
|
|
||||||
|
const toast = (id: number, message: string): Toast => ({ id, kind: 'info', message });
|
||||||
|
|
||||||
|
describe('pushToast', () => {
|
||||||
|
it('appends to an empty queue and preserves order', () => {
|
||||||
|
expect(pushToast([], toast(1, 'a'))).toEqual([toast(1, 'a')]);
|
||||||
|
expect(pushToast([toast(1, 'a')], toast(2, 'b'))).toEqual([toast(1, 'a'), toast(2, 'b')]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the newest MAX_TOASTS entries, dropping the oldest beyond the cap', () => {
|
||||||
|
let queue: Toast[] = [];
|
||||||
|
for (let id = 1; id <= MAX_TOASTS + 2; id++) queue = pushToast(queue, toast(id, `m${id}`));
|
||||||
|
expect(queue).toEqual([toast(MAX_TOASTS - 1, 'm3'), toast(MAX_TOASTS, 'm4'), toast(MAX_TOASTS + 1, 'm5'), toast(MAX_TOASTS + 2, 'm6')]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not mutate the input queue', () => {
|
||||||
|
const before = [toast(1, 'a')];
|
||||||
|
pushToast(before, toast(2, 'b'));
|
||||||
|
expect(before).toEqual([toast(1, 'a')]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useCallback, useRef, useState } from 'react';
|
||||||
|
|
||||||
|
// ISS-008 (v0.17.0): transient toast notifications — a bottom-right stack for action errors
|
||||||
|
// and game events derived from snapshot diffs. Each toast auto-dismisses after TOAST_TTL_MS;
|
||||||
|
// the queue is capped at MAX_TOASTS (oldest dropped) so an event burst can't fill the corner.
|
||||||
|
|
||||||
|
export type ToastKind = 'error' | 'info';
|
||||||
|
|
||||||
|
export interface Toast {
|
||||||
|
id: number;
|
||||||
|
kind: ToastKind;
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const TOAST_TTL_MS = 5_000;
|
||||||
|
export const MAX_TOASTS = 4;
|
||||||
|
|
||||||
|
// Pure core (unit-tested): append a toast, dropping the oldest beyond the cap.
|
||||||
|
export function pushToast(toasts: Toast[], toast: Toast): Toast[] {
|
||||||
|
return [...toasts, toast].slice(-MAX_TOASTS);
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UseToastsResult {
|
||||||
|
toasts: Toast[];
|
||||||
|
push: (kind: ToastKind, message: string) => void;
|
||||||
|
dismiss: (id: number) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useToasts(): UseToastsResult {
|
||||||
|
const [toasts, setToasts] = useState<Toast[]>([]);
|
||||||
|
const nextIdRef = useRef(1);
|
||||||
|
|
||||||
|
// Functional update — a late timer for an already-dismissed/dropped id is a no-op.
|
||||||
|
const dismiss = useCallback((id: number) => {
|
||||||
|
setToasts((current) => current.filter((t) => t.id !== id));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const push = useCallback(
|
||||||
|
(kind: ToastKind, message: string) => {
|
||||||
|
const toast: Toast = { id: nextIdRef.current++, kind, message };
|
||||||
|
setToasts((current) => pushToast(current, toast));
|
||||||
|
setTimeout(() => dismiss(toast.id), TOAST_TTL_MS);
|
||||||
|
},
|
||||||
|
[dismiss],
|
||||||
|
);
|
||||||
|
|
||||||
|
return { toasts, push, dismiss };
|
||||||
|
}
|
||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "flight-ops",
|
"name": "flight-ops",
|
||||||
"version": "0.15.0",
|
"version": "0.30.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev -p 3000",
|
"dev": "next dev -p 3000",
|
||||||
|
|||||||
Reference in New Issue
Block a user