Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
78032a2051 | ||
|
|
64da8e67bf | ||
|
|
b2d03846f5 | ||
|
|
68cfad434b | ||
|
|
5d92b5edaa | ||
|
|
4a6a8592e0 | ||
|
|
b8f321dfd5 | ||
|
|
336ed4ee7c | ||
|
|
929452ca33 |
@@ -1,5 +1,33 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## v0.42.0 — 2026-09-21 15:02
|
||||||
|
- **Auto-refuel on dispatch (ISS-082).** Manual refueling is gone — planes top up automatically at dispatch, so a grounded plane can always start any leg that fits a full tank when cash allows. `flyPlane` (`lib/game/actions.ts`) tops the tank to `min(maxFuel, max(fuel, 1.5 × required))` before departure — the same target/price terms as the removed forFlight mode: liters × FUEL_PRICE_PER_L minus the rep-scaled discount (v0.38.0), deducted from cash; unaffordable → 409 `insufficient funds` with nothing mutated, and a leg that doesn't fit even a full tank still 409s `insufficient fuel` (the backstop). The engine's auto-chain (`deliverPackages`, `lib/sim/engine.ts`) does the same at landing: when the next queued leg exceeds the landed fuel it tops up to the identical target when cash allows and chains anyway — only an unaffordable top-up grounds the plane with the queue kept intact
|
||||||
|
- **REMOVED** `POST /api/planes/:planeId/refuel` (route + route tests), the `refuelPlane()` action + `RefuelOptions` (`lib/game/actions.ts`), the left-pane "Refuel to full" section and per-leg Refuel button with their dead state/derived values (`components/LeftPane.tsx`), and the OpenAPI `/api/planes/{planeId}/refuel` path + `RefuelRequest` schema — endpoint count 14 → 13, stale refuel mentions reworded in info/state/queue/repair descriptions, and fly's description + 409 now document the auto-refuel
|
||||||
|
- **Test hook.** New POST `/api/test/set-fuel` (`FLIGHT_TEST_HOOKS=1` only): `{ planeId, fuel }` forces a plane's fuel — finite number in [0, maxFuel] (400 outside / unknown field), 404 unknown plane; sibling of set-health
|
||||||
|
- **Tests.** Unit: `refuelPlane` suite deleted; new `flyPlane` auto-refuel tests (exact top-up target + rep-discounted cost at rep 30, free no-op on a full tank, cash 0 → 409 insufficient funds with fuel unchanged, UNNT→LPPD backstop still 409s); the broken-burn test reworked to pin that ×1.5 burn raises the top-up target; `engine.test.ts`'s chain test flipped — a short tank now chains via an affordable top-up (post-top-up fuel + exact cost from the real helpers) plus a new cash-0 variant grounding with the queue intact. E2E: every `/refuel` setup/retry site (~25 across 9 specs) replaced by the set-fuel hook, heal helpers drop their refuel-and-retry guard (dispatch auto-refuels), right-pane's per-leg Refuel test and two-planes' "refuel section lists both planes" deleted in favor of one new end-to-end dispatch auto-top-up test (set-fuel drops fuel to 500 L → fly → exact cash delta from snapshot + real helpers, landed fuel = weighted burn from the topped start value), panes.spec.ts now asserts Refuel-UI absence in both panes, api.spec.ts pins thirteen endpoints
|
||||||
|
|
||||||
|
## v0.41.0 — 2026-09-21 13:26
|
||||||
|
- **Queue UI fixes (ISS-077).** Three queue-related map/UI fixes, no server logic changed:
|
||||||
|
- **Would-409 controls are disabled.** The on-board "Fly to …" button (`components/LeftPane.tsx`) is additionally disabled while the plane is flying and its destination is already active or queued (title "Already in flight queue"); the Relocate section disables its GO button for the same reason AND renders the selected plane's active/queued airports as native disabled `<option>`s. Grounded planes are untouched — their clicks go to `/fly`, which has no such conflict
|
||||||
|
- **Hover trace starts at the landing airport.** Hovering an on-board package while its carrier is FLYING now traces from the carrier's LANDING airport (`destIcao`), not its live mid-flight position (`components/Map.tsx`) — the hover previews what happens AFTER this leg lands; the solid active-leg + dotted queue layers already show where it is. Grounded / no-active-leg carriers keep today's behavior exactly (live position = the plane's airport). `hoverTraceGeoJson` returns an empty collection when start == dest, so a package destined for the active leg's destination draws nothing there — the solid layer covers it
|
||||||
|
- **Grounded queues draw dotted lines.** `queuedRoutesGeoJson` (`lib/mapData.ts`) now also draws GROUNDED ('available') planes with a non-empty queue, chaining from their current airport (`locationIcao → queue[0] → …`); flying planes keep the `[destIcao, ...queue]` chain; 'repairing' planes draw nothing. Same source/layer — no new MapLibre layer
|
||||||
|
- **Tests.** Unit: `lib/mapData.test.ts` pins the grounded chain (exact endpoints), the unknown-first-point skip, the repairing skip and the start==dest empty trace; all flying-case pins stay green. E2E: `e2e/hover.spec.ts`'s mid-flight test is reworked — a package destined for a QUEUED stop beyond the active leg, hover traces from the landing airport to that stop with no segment starting at the departure airport (deterministic: paused right after dispatch); new `e2e/queue.spec.ts` test pins the grounded two-leg chain HUB → DEST → QUEUE in the `queue-routes` layer
|
||||||
|
|
||||||
|
## v0.40.0 — 2026-09-21 13:06
|
||||||
|
- **Top-bar version link (ISS-080).** The header's version tag (`components/Map.tsx`) is now an anchor to the repo's `CHANGELOG.md` on Gitea (`app-version` testid, opens in a new tab); one small CSS rule keeps it subtle against the dark header. E2E: `e2e/map.spec.ts` pins the exact href
|
||||||
|
- **On-board ICAO tags (ISS-081).** The on-board package row in the fleet list (`components/LeftPane.tsx`) shows 4-char ICAO tags instead of full airport names — both the route span (new `onboard-route-{id}` testid) and the "Fly to …" button label + title. Other name displays (in-flight leg, plane location, map popup, open-package rows, toasts) are unchanged. E2E: one new assertion in `e2e/actions.spec.ts` pins the ICAO route on a loaded package
|
||||||
|
|
||||||
|
## v0.39.0 — 2026-09-21 12:02
|
||||||
|
- **Maintenance (ISS-069).** Planes wear out and can be repaired: distance-based health, a broken state that burns more fuel, and a repair action that grounds the plane for 3 sim days. New balance constants in `lib/game/catalog.ts` (all ponytail-tunable): `WEAR_PER_KM = 0.005`, `BROKEN_BURN_MULTIPLIER = 1.5`, `REPAIR_COST = 1_500` (flat), `REPAIR_DURATION_MS = 3 × 86_400_000`, plus the pure helper `conditionBurnMultiplier(health)` — exactly 1 above zero health, ×1.5 at/below it
|
||||||
|
- **Schema.** Two new `planes` columns in all four places: Drizzle schema (`lib/db/schema.ts`), raw DDL + guarded `ALTER TABLE … ADD COLUMN` migrations in `migrateColumns()` (pre-existing rows backfill to full health / NULL gate, mirroring the weight_kg/special precedent), and the seed insert path — starter plane in `buildSeed` (`lib/game/seed.ts`) and every `buyPlane` delivery start at `health: 100`. New plane status `'repairing'` added to the three pinned unions (schema enum, `PlaneState`, OpenAPI) plus `mapData.ts`'s feature props
|
||||||
|
- **Wear.** At landing only — `deliverPackages` (`lib/sim/engine.ts`) drops health by `WEAR_PER_KM × distanceKm` per landed leg (clamped at 0), in both the grounded and auto-chain write branches. A broken plane is one with `health ≤ 0`: it still flies, but burns ×1.5 more fuel — applied as a third factor alongside wind at ALL FIVE burn sites that hold the plane row: `flyPlane` dispatch feasibility + `refuelPlane` forFlight requirement (`lib/game/actions.ts`), engine landed-fuel + auto-chain next-leg check (`lib/sim/engine.ts`), and the live in-flight gauge in `livePlane()` (`lib/game/state.ts`). The engine's landed fuel uses the PRE-landing health (frozen at departure, like fuel) so it stays bit-consistent with the UI gauge; the chained leg's feasibility uses the post-wear value
|
||||||
|
- **Repair.** New action `repairPlane` (`lib/game/actions.ts`) + POST `/api/planes/{planeId}/repair` (no body): 404 unknown plane, 409 not grounded ("only grounded planes can be repaired"), free no-op at full health (mirrors refuel), else charges the flat `REPAIR_COST`, restores health to 100 and grounds the plane in `'repairing'` with a gate at `clockMs + REPAIR_DURATION_MS`. The engine's new `finishRepairs` pass (same shape as `expirePackages`) runs inside every advancing tick — even when nothing landed — flipping gated planes back to `'available'` and clearing the gate. While repairing, the existing `status !== 'available'` guards in load/fly/refuel/sell/abandon block everything automatically
|
||||||
|
- **Snapshot & OpenAPI.** `PlaneState` gains `health: number` + `repairUntilSimTime: number | null`; the repair endpoint is documented (200 → snapshot, 404/409). Pins updated in lockstep: `lib/openapi.test.ts` (fourteen endpoints, nine action-endpoint loop with errorCodes `['404','409']`, PlaneState key list) and `e2e/api.spec.ts`
|
||||||
|
- **UI.** The fleet rows (`components/LeftPane.tsx`) show an amber health bar (new `.health-bar`, modeled on `.fuel-bar`) + a `{n}%` readout next to the fuel text; grounded planes get a red "broken" pill at zero health and an amber "in repair" pill while the gate runs (`.status-broken` / `.status-repairing`). A Repair button appears for any grounded plane below full health — no cost preview, flat cost is server-side only
|
||||||
|
- **Test hook.** POST `/api/test/set-health` (`FLIGHT_TEST_HOOKS=1` only): `{ planeId, health?, repairUntilMs? }` forces a plane's health (finite in [0,100]) and/or sets its repair gate to `clock + repairUntilMs` — lets e2e force the broken state and shorten an active 3-day gate without flying thousands of km
|
||||||
|
- **Tests.** New unit tests: wear accumulation per landed leg + clamping at 0 across multiple legs; broken-state ×1.5 landed fuel vs a healthy control on the identical leg; `conditionBurnMultiplier` pins; `flyPlane` feasibility using the adjusted requirement (same tank flyable at full health, 409 when broken); `repairPlane` (exact cost/status/gate/health, free no-op, 409s for flying/repairing/insufficient funds, load/fly/refuel/sell all blocked while repairing) and `finishRepairs` (gate boundary + flip-back through a full `tickOnce` with nothing landed). E2E: new `e2e/maintenance.spec.ts` — the visible flow per the issue (force 42 → UI shows it; force 0 → broken pill + short full-tank leg lands with exactly the ×1.5-adjusted fuel from the real lib helpers; click Repair → exact cash drop + "in repair" pill; shorten the gate via the hook → back to service at health 100), restoring a clean starter on exit
|
||||||
|
- **E2E drift mitigation.** Wear accumulates across the whole CI run (one shared DB, workers:1) — the self-heal helpers in `e2e/right-pane.spec.ts` (`flyHomeViaApi`), `e2e/two-planes.spec.ts` (`resetFleet`) and `e2e/actions.spec.ts` (`flyHomeViaApi`) now restore full health + clear any active repair gate first, so the farthest-flyable pickers and the FAR round-trip feasibility pin never see a worn or broken starter
|
||||||
|
|
||||||
## v0.38.0 — 2026-09-21 10:47
|
## v0.38.0 — 2026-09-21 10:47
|
||||||
- **Reputation economy (ISS-072).** Reputation is no longer a dead stat — it drives the economy through three simple tunable formulas, all built on one new pure helper `repRate(reputation, perPoint, cap)` in `lib/game/catalog.ts` (linear above the starting value of 10, capped; exactly 0 at/below start so default-rep behavior is byte-identical):
|
- **Reputation economy (ISS-072).** Reputation is no longer a dead stat — it drives the economy through three simple tunable formulas, all built on one new pure helper `repRate(reputation, perPoint, cap)` in `lib/game/catalog.ts` (linear above the starting value of 10, capped; exactly 0 at/below start so default-rep behavior is byte-identical):
|
||||||
- **Cheaper plane purchases** — `buyPlane` (`lib/game/actions.ts`) charges `price × (1 − repRate(rep, PLANE_DISCOUNT_PER_REP = 0.01, MAX_PLANE_DISCOUNT = 0.4))`, rounded to 2dp; the effective cost drives both the funds check and the deduction (up to 40% off at rep ≥ 50)
|
- **Cheaper plane purchases** — `buyPlane` (`lib/game/actions.ts`) charges `price × (1 − repRate(rep, PLANE_DISCOUNT_PER_REP = 0.01, MAX_PLANE_DISCOUNT = 0.4))`, rounded to 2dp; the effective cost drives both the funds check and the deduction (up to 40% off at rep ≥ 50)
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ No manual flying — planes auto-fly assigned routes; you manage the business fr
|
|||||||
|
|
||||||
## Layout (single screen)
|
## Layout (single screen)
|
||||||
- Left pane — Assets: fleet list (plane type, status, fuel, location), wallet, reputation
|
- Left pane — Assets: fleet list (plane type, status, fuel, location), wallet, reputation
|
||||||
- Right pane — Jobs & Market: contracts between airports (reward, deadline, cargo/passengers) with accept/dispatch actions; market actions (buy/sell planes, refuel, maintenance)
|
- Right pane — Jobs & Market: contracts between airports (reward, deadline, cargo/passengers) with accept/dispatch actions; market actions (buy/sell planes, maintenance). No manual refueling — dispatch auto-tops-up the tank to 150% of the leg requirement (capped at capacity) when cash allows
|
||||||
- Middle — Map: EU airports as markers, animated plane positions along routes, active contract routes highlighted; click airport → info (runways, local time, weather); click plane → status
|
- Middle — Map: EU airports as markers, animated plane positions along routes, active contract routes highlighted; click airport → info (runways, local time, weather); click plane → status
|
||||||
|
|
||||||
## Core loop
|
## Core loop
|
||||||
|
|||||||
@@ -63,17 +63,17 @@ describe('POST /api/planes/:planeId/fly', () => {
|
|||||||
.where(eq(schema.planes.id, 'plane-starter'));
|
.where(eq(schema.planes.id, 'plane-starter'));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('rejects a leg the plane cannot fuel with 409 (burn > fuel)', async () => {
|
it('rejects a leg that does not fit even a full tank with 409 (ISS-082 backstop)', async () => {
|
||||||
const { db } = await getGameDb();
|
const { db } = await getGameDb();
|
||||||
// EDDF → LEMD ≈ 1950 km × 1.75 L/km ≈ 3400 L — far more than 1 L.
|
// UNNT → LPPD ≈ 7670 km needs ~10k L — beyond the ATR's 6300 L tank, so no auto-refuel can make it flyable.
|
||||||
await db.update(schema.planes).set({ fuel: 1 }).where(eq(schema.planes.id, 'plane-starter'));
|
await db.update(schema.planes).set({ locationIcao: 'UNNT' }).where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
const res = await post('plane-starter', { destIcao: 'LEMD' });
|
const res = await post('plane-starter', { destIcao: 'LPPD' });
|
||||||
expect(res.status).toBe(409);
|
expect(res.status).toBe(409);
|
||||||
expect(((await res.json()) as { error: string }).error).toMatch(/insufficient fuel/i);
|
expect(((await res.json()) as { error: string }).error).toMatch(/insufficient fuel/i);
|
||||||
|
|
||||||
// Refill for later tests.
|
// Put the starter back at the hub for later tests.
|
||||||
await db.update(schema.planes).set({ fuel: 6300 }).where(eq(schema.planes.id, 'plane-starter'));
|
await db.update(schema.planes).set({ locationIcao: 'EDDF' }).where(eq(schema.planes.id, 'plane-starter'));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('flies the plane and returns the full snapshot with departure + destination set', async () => {
|
it('flies the plane and returns the full snapshot with departure + destination set', async () => {
|
||||||
|
|||||||
@@ -1,171 +0,0 @@
|
|||||||
import fs from 'node:fs/promises';
|
|
||||||
import os from 'node:os';
|
|
||||||
import path from 'node:path';
|
|
||||||
import { eq } from 'drizzle-orm';
|
|
||||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
|
||||||
import * as schema from '@/lib/db/schema';
|
|
||||||
import { getGameDb } from '@/lib/db/client';
|
|
||||||
import { loadAirportsGeoJson } from '@/lib/airports';
|
|
||||||
import { haversineKm, initialBearingDeg } from '@/lib/geo';
|
|
||||||
import { weatherFor } from '@/lib/weather';
|
|
||||||
import { requiredFuelFor, windBurnFactor } from '@/lib/sim/movement';
|
|
||||||
import { FUEL_PRICE_PER_L, PLANE_TYPES } from '@/lib/game/catalog';
|
|
||||||
import { HUB_ICAO } from '@/lib/game/seed';
|
|
||||||
import { POST } from './route';
|
|
||||||
|
|
||||||
let dir: string;
|
|
||||||
|
|
||||||
beforeAll(async () => {
|
|
||||||
// Same pattern as app/api/state/route.test.ts: point the DB singleton at a
|
|
||||||
// throwaway file (fresh module registry per test file → fresh singleton).
|
|
||||||
dir = await fs.mkdtemp(path.join(os.tmpdir(), 'flight-refuel-api-'));
|
|
||||||
process.env.FLIGHT_DB_PATH = path.join(dir, 'refuel.db');
|
|
||||||
});
|
|
||||||
|
|
||||||
afterAll(async () => {
|
|
||||||
delete process.env.FLIGHT_DB_PATH;
|
|
||||||
await fs.rm(dir, { recursive: true, force: true });
|
|
||||||
});
|
|
||||||
|
|
||||||
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', () => {
|
|
||||||
it('rejects an unknown id with 404', async () => {
|
|
||||||
const res = await post('ghost');
|
|
||||||
expect(res.status).toBe(404);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('fills a partially empty tank and deducts (maxFuel − fuel) × FUEL_PRICE_PER_L from cash', async () => {
|
|
||||||
const { db } = await getGameDb();
|
|
||||||
await db.update(schema.planes).set({ fuel: 1_000 }).where(eq(schema.planes.id, 'plane-starter'));
|
|
||||||
const cashBefore = (await db.select().from(schema.account))[0].cash;
|
|
||||||
|
|
||||||
const res = await post('plane-starter');
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
|
|
||||||
const body = (await res.json()) as {
|
|
||||||
account: { cash: number };
|
|
||||||
planes: Array<{ id: string; fuel: number; maxFuel: number }>;
|
|
||||||
};
|
|
||||||
const cost = Math.round((PLANE_TYPES.atr72.maxFuel - 1_000) * FUEL_PRICE_PER_L * 100) / 100;
|
|
||||||
expect(body.account.cash).toBeCloseTo(cashBefore - cost, 6);
|
|
||||||
|
|
||||||
const plane = body.planes.find((p) => p.id === 'plane-starter')!;
|
|
||||||
expect(plane.fuel).toBe(PLANE_TYPES.atr72.maxFuel); // back to full
|
|
||||||
});
|
|
||||||
|
|
||||||
it('rejects a flying plane with 409', async () => {
|
|
||||||
const { db } = await getGameDb();
|
|
||||||
await db.update(schema.planes)
|
|
||||||
.set({ status: 'flying', departureSimTime: Date.now(), destIcao: 'LEMD' })
|
|
||||||
.where(eq(schema.planes.id, 'plane-starter'));
|
|
||||||
|
|
||||||
const res = await post('plane-starter');
|
|
||||||
expect(res.status).toBe(409);
|
|
||||||
expect(((await res.json()) as { error: string }).error).toMatch(/flying/);
|
|
||||||
|
|
||||||
// Ground it again for later tests.
|
|
||||||
await db.update(schema.planes)
|
|
||||||
.set({ status: 'available', departureSimTime: null, destIcao: null })
|
|
||||||
.where(eq(schema.planes.id, 'plane-starter'));
|
|
||||||
});
|
|
||||||
|
|
||||||
it('rejects the fill-up with 409 when cash is below the cost', async () => {
|
|
||||||
const { db } = await getGameDb();
|
|
||||||
await db.update(schema.planes).set({ fuel: 1_000 }).where(eq(schema.planes.id, 'plane-starter'));
|
|
||||||
await db.update(schema.account).set({ cash: 10 }); // cost is ~4960
|
|
||||||
|
|
||||||
const res = await post('plane-starter');
|
|
||||||
expect(res.status).toBe(409);
|
|
||||||
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 buys 150% of the weather-adjusted leg requirement', 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;
|
|
||||||
// Same wind-adjusted requirement the server computes (v0.36.0).
|
|
||||||
const w = weatherFor(HUB_ICAO);
|
|
||||||
const required = requiredFuelFor(
|
|
||||||
type.burnPerKm * windBurnFactor(w.windKt, w.windDirDeg, initialBearingDeg(from.lat, from.lon, to.lat, to.lon)),
|
|
||||||
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 }>;
|
|
||||||
};
|
|
||||||
// ISS-071: target is 150% of the requirement, capped at tank capacity.
|
|
||||||
const targetFuel = Math.min(type.maxFuel, Math.max(startFuel, required * 1.5));
|
|
||||||
const cost = Math.round((targetFuel - 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(targetFuel, 6);
|
|
||||||
|
|
||||||
// Clean up the test package.
|
|
||||||
await db.delete(schema.packages).where(eq(schema.packages.id, 'p-ff-api'));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
import { performAction, refuelPlane } from '@/lib/game/actions';
|
|
||||||
|
|
||||||
// POST /api/planes/:planeId/refuel (v0.8.0; optional body v0.16.0) — fills a grounded
|
|
||||||
// plane at the fuel price per added liter and deducts the cost from cash. The body is
|
|
||||||
// OPTIONAL: no body, {} or {mode:'full'} fill to maxFuel (the original behavior);
|
|
||||||
// {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 }> }) {
|
|
||||||
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 !== '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 }));
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { performAction, repairPlane } from '@/lib/game/actions';
|
||||||
|
|
||||||
|
// POST /api/planes/:planeId/repair (v0.39.0, ISS-069) — no body. Restores a worn-out plane to
|
||||||
|
// full health for the flat REPAIR_COST: it is grounded in "repairing" status until 3 sim days
|
||||||
|
// pass, when the engine's tick flips it back to "available". A full-health repair is a free
|
||||||
|
// no-op (cost 0). 404 unknown id; 409 plane not grounded or insufficient funds. On success
|
||||||
|
// returns the full state snapshot.
|
||||||
|
|
||||||
|
export async function POST(_req: Request, ctx: { params: Promise<{ planeId: string }> }) {
|
||||||
|
const { planeId } = await ctx.params;
|
||||||
|
return performAction((inst) => repairPlane(inst, planeId));
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import { eq } from 'drizzle-orm';
|
||||||
|
import { getGameDb, persist } from '@/lib/db/client';
|
||||||
|
import * as schema from '@/lib/db/schema';
|
||||||
|
import { getStateSnapshot } from '@/lib/game/state';
|
||||||
|
import { tickNow } from '@/lib/sim/engine';
|
||||||
|
|
||||||
|
// TEST-ONLY hook (v0.42.0, ISS-082) — lets the e2e suite force a plane's fuel level now that the
|
||||||
|
// manual /refuel endpoint is gone (dispatch auto-refuels instead). Disabled unless FLIGHT_TEST_HOOKS=1
|
||||||
|
// (set in docker-compose.yml for the e2e instance only); every other deployment 404s here. Sibling of
|
||||||
|
// /api/test/set-health — same gate, same conventions.
|
||||||
|
//
|
||||||
|
// POST /api/test/set-fuel
|
||||||
|
// body { planeId: string, fuel: number } — both required; planeId must name an existing plane
|
||||||
|
// (404 otherwise) and fuel a finite number in [0, the plane's maxFuel] (400 outside). Sets the
|
||||||
|
// planes row's fuel directly and returns the full state snapshot after ticking.
|
||||||
|
|
||||||
|
export async function POST(req: Request) {
|
||||||
|
if (process.env.FLIGHT_TEST_HOOKS !== '1') {
|
||||||
|
return Response.json({ error: 'test hooks disabled' }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
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 !== 'planeId' && key !== 'fuel') {
|
||||||
|
return Response.json({ error: `unknown field "${key}"` }, { status: 400 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const planeId = input.planeId;
|
||||||
|
if (typeof planeId !== 'string' || planeId.length === 0) {
|
||||||
|
return Response.json({ error: 'planeId is required and must be a non-empty string' }, { status: 400 });
|
||||||
|
}
|
||||||
|
const fuel = input.fuel;
|
||||||
|
if (typeof fuel !== 'number' || !Number.isFinite(fuel)) {
|
||||||
|
return Response.json({ error: 'fuel is required and must be a finite number' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const inst = await getGameDb();
|
||||||
|
await tickNow(); // clock is current before the snapshot we return (same as siblings)
|
||||||
|
const rows = await inst.db.select().from(schema.planes).where(eq(schema.planes.id, planeId));
|
||||||
|
if (!rows[0]) {
|
||||||
|
return Response.json({ error: `plane ${planeId} not found` }, { status: 404 });
|
||||||
|
}
|
||||||
|
if (fuel < 0 || fuel > rows[0].maxFuel) {
|
||||||
|
return Response.json({ error: `fuel must be in [0, maxFuel] — this plane's tank holds ${rows[0].maxFuel} L` }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
await inst.db.update(schema.planes).set({ fuel }).where(eq(schema.planes.id, planeId));
|
||||||
|
await persist(inst);
|
||||||
|
return Response.json(await getStateSnapshot());
|
||||||
|
} catch (err) {
|
||||||
|
console.error('test hook failed', err);
|
||||||
|
return Response.json({ error: 'test hook failed' }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import { eq } from 'drizzle-orm';
|
||||||
|
import { getGameDb, persist } from '@/lib/db/client';
|
||||||
|
import * as schema from '@/lib/db/schema';
|
||||||
|
import { getStateSnapshot } from '@/lib/game/state';
|
||||||
|
import { tickNow } from '@/lib/sim/engine';
|
||||||
|
|
||||||
|
// TEST-ONLY hook (v0.39.0, ISS-069) — lets the e2e suite force a plane's health and/or shorten an
|
||||||
|
// active repair gate without flying thousands of km or waiting 3 sim days. Disabled unless
|
||||||
|
// FLIGHT_TEST_HOOKS=1 (set in docker-compose.yml for the e2e instance only); every other
|
||||||
|
// deployment 404s here. Sibling of /api/test/add-cash — same gate, same conventions.
|
||||||
|
//
|
||||||
|
// POST /api/test/set-health
|
||||||
|
// body { planeId: string, health?: number, repairUntilMs?: number }
|
||||||
|
// - planeId is required and must name an existing plane (404 otherwise);
|
||||||
|
// - at least one of health / repairUntilMs must be present;
|
||||||
|
// - health must be a finite number in [0, 100];
|
||||||
|
// - repairUntilMs sets repair_until_sim_time = clock + repairUntilMs (the expire-package
|
||||||
|
// near-term-gate precedent) so the next advancing tick flips a shortened repair back.
|
||||||
|
// Returns the full state snapshot after ticking.
|
||||||
|
|
||||||
|
export async function POST(req: Request) {
|
||||||
|
if (process.env.FLIGHT_TEST_HOOKS !== '1') {
|
||||||
|
return Response.json({ error: 'test hooks disabled' }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
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 !== 'planeId' && key !== 'health' && key !== 'repairUntilMs') {
|
||||||
|
return Response.json({ error: `unknown field "${key}"` }, { status: 400 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const planeId = input.planeId;
|
||||||
|
if (typeof planeId !== 'string' || planeId.length === 0) {
|
||||||
|
return Response.json({ error: 'planeId is required and must be a non-empty string' }, { status: 400 });
|
||||||
|
}
|
||||||
|
let health: number | undefined;
|
||||||
|
if (input.health !== undefined) {
|
||||||
|
if (typeof input.health !== 'number' || !Number.isFinite(input.health) || input.health < 0 || input.health > 100) {
|
||||||
|
return Response.json({ error: 'health must be a finite number in [0, 100]' }, { status: 400 });
|
||||||
|
}
|
||||||
|
health = input.health;
|
||||||
|
}
|
||||||
|
let repairUntilMs: number | undefined;
|
||||||
|
if (input.repairUntilMs !== undefined) {
|
||||||
|
if (typeof input.repairUntilMs !== 'number' || !Number.isFinite(input.repairUntilMs)) {
|
||||||
|
return Response.json({ error: 'repairUntilMs must be a finite number' }, { status: 400 });
|
||||||
|
}
|
||||||
|
repairUntilMs = input.repairUntilMs;
|
||||||
|
}
|
||||||
|
if (health === undefined && repairUntilMs === undefined) {
|
||||||
|
return Response.json({ error: 'at least one of health or repairUntilMs is required' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const inst = await getGameDb();
|
||||||
|
const sim = await tickNow(); // clock is current before we set the gate (same as siblings)
|
||||||
|
const rows = await inst.db.select().from(schema.planes).where(eq(schema.planes.id, planeId));
|
||||||
|
if (!rows[0]) {
|
||||||
|
return Response.json({ error: `plane ${planeId} not found` }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const sets: Partial<Pick<schema.PlaneRow, 'health' | 'repairUntilSimTime'>> = {};
|
||||||
|
if (health !== undefined) sets.health = health;
|
||||||
|
if (repairUntilMs !== undefined) sets.repairUntilSimTime = Math.round(sim.clockMs + repairUntilMs);
|
||||||
|
await inst.db.update(schema.planes).set(sets).where(eq(schema.planes.id, planeId));
|
||||||
|
await persist(inst);
|
||||||
|
return Response.json(await getStateSnapshot());
|
||||||
|
} catch (err) {
|
||||||
|
console.error('test hook failed', err);
|
||||||
|
return Response.json({ error: 'test hook failed' }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -48,6 +48,16 @@ body {
|
|||||||
color: #94a3b8;
|
color: #94a3b8;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ISS-080 (v0.40.0): the version tag links to the repo's CHANGELOG.md — keep it subtle, like the rest of the header. */
|
||||||
|
.app-header a {
|
||||||
|
color: #7dd3fc;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.app-header a:hover {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
/* Style switcher — kept subtle, like the version tag. */
|
/* Style switcher — kept subtle, like the version tag. */
|
||||||
.style-switch {
|
.style-switch {
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
@@ -214,6 +224,17 @@ body {
|
|||||||
color: #bfdbfe;
|
color: #bfdbfe;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* v0.39.0 (ISS-069): maintenance pills on fleet rows — broken = red, in repair = amber. */
|
||||||
|
.status-broken {
|
||||||
|
background: rgba(239, 68, 68, 0.25);
|
||||||
|
color: #fecaca;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-repairing {
|
||||||
|
background: rgba(245, 158, 11, 0.25);
|
||||||
|
color: #fde68a;
|
||||||
|
}
|
||||||
|
|
||||||
/* v0.37.0 (ISS-073): special-status pill on package rows — sky-blue accent, modeled on .plane-status. */
|
/* v0.37.0 (ISS-073): special-status pill on package rows — sky-blue accent, modeled on .plane-status. */
|
||||||
.special-badge {
|
.special-badge {
|
||||||
font-size: 11px;
|
font-size: 11px;
|
||||||
@@ -237,6 +258,26 @@ body {
|
|||||||
background: #34d399;
|
background: #34d399;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* v0.39.0 (ISS-069): health bar — modeled on .fuel-bar, amber fill. */
|
||||||
|
.health-bar {
|
||||||
|
height: 4px;
|
||||||
|
border-radius: 2px;
|
||||||
|
background: rgba(148, 163, 184, 0.25);
|
||||||
|
margin: 2px 0 4px;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.health-bar > div {
|
||||||
|
height: 100%;
|
||||||
|
border-radius: 2px;
|
||||||
|
background: #f59e0b;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* v0.39.0 (ISS-069): the per-plane Repair button sits under the readout row. */
|
||||||
|
.repair-btn {
|
||||||
|
margin-top: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
.plane-sub {
|
.plane-sub {
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
|
|||||||
+1
-1
@@ -44,7 +44,7 @@ export default function Home() {
|
|||||||
return (
|
return (
|
||||||
<div className="app-shell">
|
<div className="app-shell">
|
||||||
{/* ISS-021 (v0.20.0) — applySnapshot also reaches the left pane: its On board section's
|
{/* ISS-021 (v0.20.0) — applySnapshot also reaches the left pane: its On board section's
|
||||||
refuel/fly/abandon actions push their response snapshot into the shared state */}
|
fly/abandon actions push their response snapshot into the shared state */}
|
||||||
<LeftPane state={state} loading={loading} error={error} onRefresh={refresh} applySnapshot={applySnapshot} onHover={setHovered} onError={onError} />
|
<LeftPane state={state} loading={loading} error={error} onRefresh={refresh} applySnapshot={applySnapshot} onHover={setHovered} onError={onError} />
|
||||||
{/* v0.11.0 — the same polled snapshot drives the map's plane markers + route lines;
|
{/* 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
|
ISS-010 (v0.18.0) — applySnapshot lets the airport popup's Relocate row push its
|
||||||
|
|||||||
+55
-87
@@ -3,7 +3,7 @@
|
|||||||
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 { GeoJsonFeatureCollection } from '@/lib/airports';
|
||||||
import type { PlaneState, StateSnapshot } from '@/lib/game/state';
|
import type { PlaneState, StateSnapshot } from '@/lib/game/state';
|
||||||
import { FUEL_DISCOUNT_PER_REP, MAX_FUEL_DISCOUNT, PLANE_TYPES, repRate } from '@/lib/game/catalog';
|
import { PLANE_TYPES } from '@/lib/game/catalog';
|
||||||
import { abandonPenalty } from '@/lib/game/penalty';
|
import { abandonPenalty } from '@/lib/game/penalty';
|
||||||
import { formatCash, formatDeadlineRelative, formatFuel, formatSimClock, formatSpecialLabel } from '@/lib/format';
|
import { formatCash, formatDeadlineRelative, formatFuel, formatSimClock, formatSpecialLabel } from '@/lib/format';
|
||||||
import { TIME_SCALES, scaleToSlider, sliderToScale } from '@/lib/timeScale';
|
import { TIME_SCALES, scaleToSlider, sliderToScale } from '@/lib/timeScale';
|
||||||
@@ -19,7 +19,7 @@ interface LeftPaneProps {
|
|||||||
// 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
|
// ISS-021 (v0.20.0): push the full snapshot returned by an action endpoint into the shared shell
|
||||||
// state — needed now that the per-plane cargo rows' refuel/fly/abandon actions live in this pane.
|
// state — needed now that the per-plane cargo rows' fly/abandon actions live in this pane.
|
||||||
applySnapshot: (snapshot: StateSnapshot) => void;
|
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;
|
||||||
@@ -101,11 +101,6 @@ export default function LeftPane({ state, loading, error, onRefresh, applySnapsh
|
|||||||
const [relocatePlaneId, setRelocatePlaneId] = useState<string | null>(null);
|
const [relocatePlaneId, setRelocatePlaneId] = useState<string | null>(null);
|
||||||
const [relocateDestIcao, setRelocateDestIcao] = 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-010 (v0.18.0): one-time /api/airports fetch per page life — destination options for the
|
// 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;
|
// 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
|
// on failure airportOptions stays null and the Relocate button simply remains disabled. Moved here
|
||||||
@@ -202,27 +197,16 @@ export default function LeftPane({ state, loading, error, onRefresh, applySnapsh
|
|||||||
// endpoint (pure repositioning, no package needed since v0.12.0). Moved here from the right-pane
|
// 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.
|
// market row; with state null both fall back to null and the section isn't rendered.
|
||||||
// ISS-053 (v0.32.0): widened from grounded-only to ALL planes — a flying plane's relocation is
|
// ISS-053 (v0.32.0): widened from grounded-only to ALL planes — a flying plane's relocation is
|
||||||
// queued instead of started immediately (see relocate-go below). `grounded` stays for Refuel.
|
// queued instead of started immediately (see relocate-go below).
|
||||||
const relocatable = state ? state.planes : [];
|
const relocatable = state ? state.planes : [];
|
||||||
const relocatePlane = relocatable.find((p) => p.id === relocatePlaneId) ?? relocatable[0] ?? null;
|
const relocatePlane = relocatable.find((p) => p.id === relocatePlaneId) ?? relocatable[0] ?? null;
|
||||||
const relocateDest =
|
const relocateDest =
|
||||||
airportOptions === null ? null : airportOptions.find((a) => a.icao === relocateDestIcao) ?? airportOptions[0] ?? null;
|
airportOptions === null ? null : airportOptions.find((a) => a.icao === relocateDestIcao) ?? airportOptions[0] ?? null;
|
||||||
|
// ISS-077 (v0.41.0): while flying, the Relocate click would POST /queue — block it when the selected
|
||||||
// ISS-035 (v0.23.0): Refuel-to-full — any GROUNDED plane with fuel below max can be topped up via the
|
// destination is already active or queued (the server rejects that with 409). Grounded planes are unaffected.
|
||||||
// existing refuel endpoint (no body → server defaults to mode 'full'). Moved here from the right-pane
|
const relocateBlocked =
|
||||||
// market row; grounded-only, and with state null falls back to null.
|
relocatePlane?.status === 'flying' && relocateDest !== null &&
|
||||||
const grounded = relocatable.filter((p) => p.status === 'available');
|
(relocatePlane.destIcao === relocateDest.icao || relocatePlane.queue.includes(relocateDest.icao));
|
||||||
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;
|
|
||||||
// v0.38.0 (ISS-072): rep-scaled preview — same formula as the server's refuelPlane 'full' mode.
|
|
||||||
const fuelDiscountRate = state ? repRate(state.account.reputation, FUEL_DISCOUNT_PER_REP, MAX_FUEL_DISCOUNT) : 0;
|
|
||||||
const refuelCost =
|
|
||||||
refuelPlane && state
|
|
||||||
? Math.round((refuelPlane.maxFuel - refuelPlane.fuel) * state.fuelPricePerL * (1 - fuelDiscountRate) * 100) / 100
|
|
||||||
: 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
|
||||||
@@ -368,19 +352,50 @@ export default function LeftPane({ state, loading, error, onRefresh, applySnapsh
|
|||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<span className="plane-status status-available">{p.locationIcao}</span>
|
<>
|
||||||
|
<span className="plane-status status-available">{p.locationIcao}</span>
|
||||||
|
{/* v0.39.0 (ISS-069): maintenance pills — "in repair" while the gate runs, "broken" at zero health. */}
|
||||||
|
{p.status === 'repairing' && (
|
||||||
|
<span data-testid={`plane-repairing-${p.id}`} className="plane-status status-repairing">in repair</span>
|
||||||
|
)}
|
||||||
|
{p.health <= 0 && (
|
||||||
|
<span data-testid={`plane-broken-${p.id}`} className="plane-status status-broken">broken</span>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="fuel-bar" aria-hidden="true">
|
<div className="fuel-bar" aria-hidden="true">
|
||||||
<div style={{ width: `${Math.max(0, Math.min(100, (p.fuel / p.maxFuel) * 100))}%` }} />
|
<div style={{ width: `${Math.max(0, Math.min(100, (p.fuel / p.maxFuel) * 100))}%` }} />
|
||||||
</div>
|
</div>
|
||||||
|
{/* v0.39.0 (ISS-069): health bar — sibling of the fuel bar, amber fill. */}
|
||||||
|
<div className="health-bar" aria-hidden="true">
|
||||||
|
<div style={{ width: `${Math.max(0, Math.min(100, p.health))}%` }} />
|
||||||
|
</div>
|
||||||
<div className="plane-sub">
|
<div className="plane-sub">
|
||||||
<span data-testid={`plane-fuel-${p.id}`}>{formatFuel(p.fuel, p.maxFuel)}</span>
|
<span data-testid={`plane-fuel-${p.id}`}>{formatFuel(p.fuel, p.maxFuel)}</span>
|
||||||
|
{/* v0.39.0 (ISS-069): health percentage next to the fuel readout. */}
|
||||||
|
<span data-testid={`plane-health-${p.id}`}>{Math.round(p.health)}%</span>
|
||||||
<span data-testid={`plane-loadout-${p.id}`}>{loadoutFor(state, p)}</span>
|
<span data-testid={`plane-loadout-${p.id}`}>{loadoutFor(state, p)}</span>
|
||||||
<span className="plane-loc">{planeLocation(p)}</span>
|
<span className="plane-loc">{planeLocation(p)}</span>
|
||||||
</div>
|
</div>
|
||||||
|
{/* v0.39.0 (ISS-069): repair — grounded plane with worn health; flat cost is server-side only (no preview). */}
|
||||||
|
{p.status === 'available' && p.health < 100 && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid={`repair-${p.id}`}
|
||||||
|
className="pane-btn repair-btn"
|
||||||
|
disabled={actionsBusy}
|
||||||
|
onClick={() => void runAction(`/api/planes/${p.id}/repair`)}
|
||||||
|
>
|
||||||
|
Repair
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
{cargo.map((pkg) => {
|
{cargo.map((pkg) => {
|
||||||
const penalty = abandonPenalty(pkg, clockMs);
|
const penalty = abandonPenalty(pkg, clockMs);
|
||||||
|
// ISS-077 (v0.41.0): while flying the click would POST /queue — disable it when the
|
||||||
|
// destination is already active or queued (the server rejects that with 409). Grounded
|
||||||
|
// clicks go to /fly, which has no such conflict.
|
||||||
|
const alreadyQueued = p.status === 'flying' && (p.destIcao === pkg.destIcao || p.queue.includes(pkg.destIcao));
|
||||||
return (
|
return (
|
||||||
// ISS-025 (v0.22.0): hovering a loaded package draws its full origin→dest trace on the map —
|
// 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
|
// same as job-list rows — and keeps this plane's halo lit via planeId. Leaving the row restores
|
||||||
@@ -397,25 +412,19 @@ export default function LeftPane({ state, loading, error, onRefresh, applySnapsh
|
|||||||
type="button"
|
type="button"
|
||||||
data-testid={`fly-to-${pkg.id}`}
|
data-testid={`fly-to-${pkg.id}`}
|
||||||
className="pane-btn onboard-fly-btn"
|
className="pane-btn onboard-fly-btn"
|
||||||
disabled={actionsBusy}
|
disabled={actionsBusy || alreadyQueued}
|
||||||
|
title={alreadyQueued ? 'Already in flight queue' : undefined}
|
||||||
// ISS-053 (v0.32.0): a flying plane can't start another leg — the click queues it instead,
|
// ISS-053 (v0.32.0): a flying plane can't start another leg — the click queues it instead,
|
||||||
// so "Fly to …" works from any state and the queue needs no dedicated input.
|
// so "Fly to …" works from any state and the queue needs no dedicated input.
|
||||||
onClick={() => void runAction(`/api/planes/${p.id}/${p.status === 'flying' ? 'queue' : 'fly'}`, { destIcao: pkg.destIcao })}
|
onClick={() => void runAction(`/api/planes/${p.id}/${p.status === 'flying' ? 'queue' : 'fly'}`, { destIcao: pkg.destIcao })}
|
||||||
>
|
>
|
||||||
<span className="onboard-fly-label" title={`Fly to ${pkg.destName}`}>
|
{/* ISS-081 (v0.40.0): ICAO tags instead of full airport names. */}
|
||||||
Fly to {pkg.destName}
|
<span className="onboard-fly-label" title={`Fly to ${pkg.destIcao}`}>
|
||||||
|
Fly to {pkg.destIcao}
|
||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
|
{/* ISS-082 (v0.42.0): the per-leg Refuel button is gone — dispatch auto-refuels. */}
|
||||||
<div className="onboard-actions">
|
<div className="onboard-actions">
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
data-testid={`refuel-for-${pkg.id}`}
|
|
||||||
className="pane-btn"
|
|
||||||
disabled={actionsBusy || p.status !== 'available'}
|
|
||||||
onClick={() => void runAction(`/api/planes/${p.id}/refuel`, { mode: 'forFlight', packageId: pkg.id })}
|
|
||||||
>
|
|
||||||
Refuel
|
|
||||||
</button>
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
data-testid={`abandon-${pkg.id}`}
|
data-testid={`abandon-${pkg.id}`}
|
||||||
@@ -428,7 +437,10 @@ export default function LeftPane({ state, loading, error, onRefresh, applySnapsh
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div className="contract-sub">
|
<div className="contract-sub">
|
||||||
<span className="contract-route">{pkg.originName} → {pkg.destName}</span>
|
{/* ISS-081 (v0.40.0): ICAO tags instead of full airport names. */}
|
||||||
|
<span data-testid={`onboard-route-${pkg.id}`} className="contract-route">
|
||||||
|
{pkg.originIcao} → {pkg.destIcao}
|
||||||
|
</span>
|
||||||
{/* v0.37.0 (ISS-073): special-status badge — rendered only when the package has one. */}
|
{/* v0.37.0 (ISS-073): special-status badge — rendered only when the package has one. */}
|
||||||
{pkg.special && (
|
{pkg.special && (
|
||||||
<span data-testid={`package-special-${pkg.id}`} className="special-badge">
|
<span data-testid={`package-special-${pkg.id}`} className="special-badge">
|
||||||
@@ -520,7 +532,9 @@ export default function LeftPane({ state, loading, error, onRefresh, applySnapsh
|
|||||||
onChange={(e) => setRelocateDestIcao(e.target.value || null)}
|
onChange={(e) => setRelocateDestIcao(e.target.value || null)}
|
||||||
>
|
>
|
||||||
{airportOptions?.map((a) => (
|
{airportOptions?.map((a) => (
|
||||||
<option key={a.icao} value={a.icao}>
|
// ISS-077 (v0.41.0): a flying plane's active/queued airports can't be re-selected — the
|
||||||
|
// server would reject them with 409; native disabled options, no text change.
|
||||||
|
<option key={a.icao} value={a.icao} disabled={relocatePlane?.status === 'flying' && (relocatePlane.destIcao === a.icao || relocatePlane.queue.includes(a.icao))}>
|
||||||
{a.name}
|
{a.name}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
@@ -529,7 +543,7 @@ export default function LeftPane({ state, loading, error, onRefresh, applySnapsh
|
|||||||
type="button"
|
type="button"
|
||||||
data-testid="relocate-go"
|
data-testid="relocate-go"
|
||||||
className="pane-btn"
|
className="pane-btn"
|
||||||
disabled={actionsBusy || relocatePlane === null || relocateDest === null}
|
disabled={actionsBusy || relocatePlane === null || relocateDest === null || relocateBlocked}
|
||||||
// ISS-053 (v0.32.0): a flying plane can't start another leg — queue it instead, so the
|
// ISS-053 (v0.32.0): a flying plane can't start another leg — queue it instead, so the
|
||||||
// relocation takes off when the current one lands.
|
// relocation takes off when the current one lands.
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
@@ -543,53 +557,7 @@ export default function LeftPane({ state, loading, error, onRefresh, applySnapsh
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
{/* ISS-035 (v0.23.0): moved here from the right-pane market row — it belongs with everything else
|
{/* ISS-082 (v0.42.0): the "Refuel to full" section is gone — dispatch auto-refuels instead. */}
|
||||||
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 the fleet rows (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>
|
|
||||||
{/* v0.38.0 (ISS-072): rep discount hint — only when the account actually gets one. */}
|
|
||||||
{fuelDiscountRate > 0 && (
|
|
||||||
<span data-testid="refuel-discount" className="special-badge">−{Math.round(fuelDiscountRate * 100)}%</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>
|
||||||
|
|||||||
+14
-2
@@ -153,10 +153,20 @@ export default function FlightMap({ state, hovered, applySnapshot }: MapProps) {
|
|||||||
// ISS-040 (v0.23.2): an on-board package's trace starts from the carrier plane's LIVE position,
|
// 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
|
// 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.
|
// has departed with cargo still loaded. No carrier in state yet → fall back to the ICAO trace.
|
||||||
|
// ISS-077 (v0.41.0): a FLYING carrier's trace starts at its LANDING airport (destIcao), not the
|
||||||
|
// live mid-flight position — the hover previews what happens AFTER this leg lands, and the solid
|
||||||
|
// active-leg + dotted queue layers already show where it is now. Grounded / no active leg keeps
|
||||||
|
// today's behavior exactly (live position = the plane's airport). destIcao missing from the
|
||||||
|
// index → fall back to the live position rather than guessing.
|
||||||
const idx = airportsIndexRef.current ?? new Map();
|
const idx = airportsIndexRef.current ?? new Map();
|
||||||
const carrier = h?.kind === 'package' && h.planeId ? stateRef.current?.planes.find((p) => p.id === h.planeId) : undefined;
|
const carrier = h?.kind === 'package' && h.planeId ? stateRef.current?.planes.find((p) => p.id === h.planeId) : undefined;
|
||||||
|
const landing = carrier?.status === 'flying' && carrier.destIcao ? idx.get(carrier.destIcao) : undefined;
|
||||||
void hoverSource.setData(
|
void hoverSource.setData(
|
||||||
carrier ? hoverTraceGeoJson({ lat: carrier.lat, lon: carrier.lon }, toIcao, idx) : hoverRouteGeoJson(fromIcao, toIcao, idx),
|
landing
|
||||||
|
? hoverTraceGeoJson(landing, toIcao, idx)
|
||||||
|
: 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 —
|
// Package hovers ring BOTH endpoints (v0.15.0 behavior); 'route' hovers ring the TARGET only —
|
||||||
@@ -537,7 +547,9 @@ export default function FlightMap({ state, hovered, applySnapshot }: MapProps) {
|
|||||||
<div className="map-wrap">
|
<div className="map-wrap">
|
||||||
<header data-testid="app-header" className="app-header">
|
<header data-testid="app-header" className="app-header">
|
||||||
<h1>Flight Ops</h1>
|
<h1>Flight Ops</h1>
|
||||||
<small>v{pkg.version}</small>
|
<a data-testid="app-version" href="https://git.kkhost.pl/OpenCode/Flight-Ops/src/branch/master/CHANGELOG.md" target="_blank" rel="noreferrer">
|
||||||
|
<small>v{pkg.version}</small>
|
||||||
|
</a>
|
||||||
<select
|
<select
|
||||||
data-testid="style-switch"
|
data-testid="style-switch"
|
||||||
className="style-switch"
|
className="style-switch"
|
||||||
|
|||||||
@@ -24,6 +24,8 @@ function plane(over: Partial<PlaneState> & Pick<PlaneState, 'id'>): PlaneState {
|
|||||||
departureSimTime: null,
|
departureSimTime: null,
|
||||||
lat: 50,
|
lat: 50,
|
||||||
lon: 8.5,
|
lon: 8.5,
|
||||||
|
health: 100, // v0.39.0 (ISS-069) — full-health fixture default
|
||||||
|
repairUntilSimTime: null,
|
||||||
queue: [],
|
queue: [],
|
||||||
...over,
|
...over,
|
||||||
};
|
};
|
||||||
|
|||||||
+27
-52
@@ -5,8 +5,6 @@ import { expect, test } from '@playwright/test';
|
|||||||
import { initialBearingDeg } from '../lib/geo';
|
import { initialBearingDeg } from '../lib/geo';
|
||||||
import { weatherFor } from '../lib/weather';
|
import { weatherFor } from '../lib/weather';
|
||||||
import { windBurnFactor } from '../lib/sim/movement';
|
import { windBurnFactor } from '../lib/sim/movement';
|
||||||
// v0.38.0 (ISS-072) — reputation discounts: expectations computed from the LIVE snapshot's rep with the real helpers.
|
|
||||||
import { FUEL_DISCOUNT_PER_REP, FUEL_PRICE_PER_L, MAX_FUEL_DISCOUNT, repRate } from '../lib/game/catalog';
|
|
||||||
|
|
||||||
// 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
|
||||||
@@ -18,12 +16,9 @@ import { FUEL_DISCOUNT_PER_REP, FUEL_PRICE_PER_L, MAX_FUEL_DISCOUNT, repRate } f
|
|||||||
|
|
||||||
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 — 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 (v0.16.0 weight-proportional burn) + lib/game/catalog.ts (atr72).
|
// Mirrors lib/sim/movement.ts (v0.16.0 weight-proportional burn).
|
||||||
const FUEL_DENSITY_KG_PER_L = 0.8; // Jet-A1 density — must match FUEL_DENSITY_KG_PER_L in movement.ts
|
const FUEL_DENSITY_KG_PER_L = 0.8; // Jet-A1 density — must match FUEL_DENSITY_KG_PER_L in movement.ts
|
||||||
// FUEL_PRICE_PER_L is imported from ../lib/game/catalog (v0.38.0) instead of mirrored here.
|
|
||||||
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;
|
||||||
|
|
||||||
@@ -79,6 +74,14 @@ async function postSim(page: Page, body: Record<string, unknown>): Promise<void>
|
|||||||
expect(res.ok()).toBeTruthy();
|
expect(res.ok()).toBeTruthy();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Test hook (FLIGHT_TEST_HOOKS=1): top a plane's tank back to full — replaces the removed /refuel
|
||||||
|
// endpoint (ISS-082). Reads maxFuel from the snapshot so no catalog mirror is needed.
|
||||||
|
async function setFuelFull(page: Page, planeId: string): Promise<void> {
|
||||||
|
const s = await getState(page);
|
||||||
|
const p = s.planes.find((x) => x.id === planeId)!;
|
||||||
|
expect((await page.request.post('/api/test/set-fuel', { data: { planeId, fuel: p.maxFuel } })).status()).toBe(200);
|
||||||
|
}
|
||||||
|
|
||||||
// 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
|
// ISS-041 also clears pause: a landing pauses the sim, so any fast-forward after one must
|
||||||
@@ -118,7 +121,11 @@ 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> {
|
||||||
let s = await getState(page);
|
// v0.39.0 (ISS-069): wear accumulates across the shared CI DB — restore full health and clear any
|
||||||
|
// active repair gate from an interrupted run before the steps below act on the starter, so the
|
||||||
|
// exact-fuel pins never see a worn or broken plane (broken planes burn ×1.5 more).
|
||||||
|
expect((await page.request.post('/api/test/set-health', { data: { planeId: 'plane-starter', health: 100, repairUntilMs: 0 } })).status()).toBe(200);
|
||||||
|
let s = await getState(page); // ticks — a shortened gate flips the plane back to available here
|
||||||
let plane = s.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×).
|
||||||
@@ -156,7 +163,7 @@ async function flyHomeViaApi(page: Page): Promise<void> {
|
|||||||
|
|
||||||
|
|
||||||
test('full core loop via UI: load → fly to destination → exact reward + rep on arrival', async ({ page }) => {
|
test('full core loop via UI: load → fly to destination → exact reward + rep on arrival', async ({ page }) => {
|
||||||
test.setTimeout(300_000); // self-heal (worst case ~20 s at 1000×) + two short flights + refuel
|
test.setTimeout(300_000); // self-heal (worst case ~20 s at 1000×) + two short flights
|
||||||
// Self-heal: the starter plane may be anywhere from a previous run/spec.
|
// Self-heal: the starter plane may be anywhere from a previous run/spec.
|
||||||
await flyHomeViaApi(page);
|
await flyHomeViaApi(page);
|
||||||
const before = await getState(page);
|
const before = await getState(page);
|
||||||
@@ -188,8 +195,10 @@ test('full core loop via UI: load → fly to destination → exact reward + rep
|
|||||||
// package shows as loaded on the starter in the on-board section.
|
// package shows as loaded on the starter in the on-board section.
|
||||||
const onboardRow = page.getByTestId(`onboard-package-${pkg.id}`);
|
const onboardRow = page.getByTestId(`onboard-package-${pkg.id}`);
|
||||||
await expect(onboardRow, 'loaded package appears in the on-board list').toBeVisible();
|
await expect(onboardRow, 'loaded package appears in the on-board list').toBeVisible();
|
||||||
|
// ISS-081 (v0.40.0): the on-board route shows ICAO tags, not full airport names.
|
||||||
|
await expect(page.getByTestId(`onboard-route-${pkg.id}`)).toContainText(`${HUB} → ${nearest.icao}`);
|
||||||
|
|
||||||
// FLY via the UI: click the destination name button in the on-board list.
|
// FLY via the UI: click the fly-to button in the on-board list (ISS-081: ICAO label).
|
||||||
const flyBtn = page.getByTestId(`fly-to-${pkg.id}`);
|
const flyBtn = page.getByTestId(`fly-to-${pkg.id}`);
|
||||||
await expect(flyBtn).toBeEnabled();
|
await expect(flyBtn).toBeEnabled();
|
||||||
await flyBtn.click();
|
await flyBtn.click();
|
||||||
@@ -241,15 +250,8 @@ test('full core loop via UI: load → fly to destination → exact reward + rep
|
|||||||
6,
|
6,
|
||||||
);
|
);
|
||||||
|
|
||||||
// Refuel via the API: cost = (maxFuel − fuel) × FUEL_PRICE_PER_L, rep-scaled (v0.38.0, ISS-072), deducted exactly.
|
// ISS-082 (v0.42.0): manual refuel is gone — the return leg below auto-refuels on dispatch; the
|
||||||
const refuelRes = await page.request.post(`/api/planes/${planeId}/refuel`);
|
// exact top-up cost delta is pinned in e2e/right-pane.spec.ts instead of here.
|
||||||
expect(refuelRes.ok()).toBeTruthy();
|
|
||||||
s = await getState(page);
|
|
||||||
const afterRefuel = s.planes.find((p) => p.id === planeId)!;
|
|
||||||
expect(afterRefuel.fuel).toBe(afterRefuel.maxFuel); // back to full
|
|
||||||
const fuelRate = repRate(s.account.reputation, FUEL_DISCOUNT_PER_REP, MAX_FUEL_DISCOUNT);
|
|
||||||
const refuelCost = Math.round((afterRefuel.maxFuel - landed.fuel) * FUEL_PRICE_PER_L * (1 - fuelRate) * 100) / 100;
|
|
||||||
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). ISS-041: the
|
// 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).
|
// arrival above paused the sim, so re-set SCALE for the return leg (setScale clears pause).
|
||||||
@@ -341,9 +343,9 @@ 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. ISS-041: the LEMD arrival above paused the sim, so
|
// Restore: top up + 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).
|
// 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 setFuelFull(page, 'plane-starter');
|
||||||
await setScale(page, SCALE);
|
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();
|
||||||
@@ -351,7 +353,7 @@ test('expired packages deliver and abandon with no reward and no penalty', async
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('load and fly validation paths (404 / 409 / 400)', async ({ page }) => {
|
test('load and fly validation paths (404 / 409 / 400)', async ({ page }) => {
|
||||||
test.setTimeout(600_000); // the FAR round trip alone is ~30 s real time at 1000×
|
test.setTimeout(300_000); // self-heal + one short hop each way at scale 1000
|
||||||
await flyHomeViaApi(page);
|
await flyHomeViaApi(page);
|
||||||
|
|
||||||
// Load a package whose origin the plane is not at → 409.
|
// Load a package whose origin the plane is not at → 409.
|
||||||
@@ -389,37 +391,10 @@ test('load and fly validation paths (404 / 409 / 400)', async ({ page }) => {
|
|||||||
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 (v0.16.0 weighted burn): a full tank covers the FAR round trip —
|
// ISS-082 (v0.42.0): the old "second outbound must 409 on insufficient fuel" pin is gone — dispatch
|
||||||
// the plane gets lighter as fuel burns off, so both legs fit — but landing back at the
|
// auto-refuels any full-tank-flyable leg, so a partial tank no longer blocks it. The remaining
|
||||||
// hub leaves too little for ANOTHER long leg: the second outbound must 409.
|
// insufficient-fuel case (a leg that doesn't fit even a FULL tank) is pinned in the unit tests and
|
||||||
const s0 = await getState(page);
|
// app/api/planes/[planeId]/fly/route.test.ts instead of spending ~60 s of CI time on a FAR round trip here.
|
||||||
const starter = s0.planes.find((p) => p.id === 'plane-starter')!;
|
|
||||||
expect(starter.locationIcao).toBe(HUB); // landed back at the hub from the hop above
|
|
||||||
if (starter.fuel < starter.maxFuel) {
|
|
||||||
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 } });
|
|
||||||
expect(farRes.ok()).toBeTruthy();
|
|
||||||
await setScale(page, SCALE);
|
|
||||||
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.status), { timeout: 240_000 }).toBe('available');
|
|
||||||
|
|
||||||
const sFar = await getState(page);
|
|
||||||
const atFar = sFar.planes.find((p) => p.id === 'plane-starter')!;
|
|
||||||
expect(atFar.locationIcao).toBe(FAR);
|
|
||||||
// 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 } });
|
|
||||||
expect(backRes.ok()).toBeTruthy();
|
|
||||||
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).
|
||||||
|
|||||||
+1
-1
@@ -31,7 +31,7 @@ test('GET /api/openapi serves the spec with all thirteen endpoints and the packa
|
|||||||
'/api/planes/{planeId}/fly',
|
'/api/planes/{planeId}/fly',
|
||||||
'/api/planes/{planeId}/queue',
|
'/api/planes/{planeId}/queue',
|
||||||
'/api/planes/{planeId}/queue/cancel',
|
'/api/planes/{planeId}/queue/cancel',
|
||||||
'/api/planes/{planeId}/refuel',
|
'/api/planes/{planeId}/repair', // v0.39.0 (ISS-069)
|
||||||
'/api/sim',
|
'/api/sim',
|
||||||
'/api/state',
|
'/api/state',
|
||||||
'/api/version',
|
'/api/version',
|
||||||
|
|||||||
+53
-38
@@ -15,6 +15,8 @@ const SCALE = 1000; // fastest sim speed (v0.14.0 ladder top) — keeps flights
|
|||||||
const HUB = 'EDDF'; // must match HUB_ICAO in lib/game/seed.ts
|
const HUB = 'EDDF'; // must match HUB_ICAO in lib/game/seed.ts
|
||||||
// Madrid–Barajas — same long leg as e2e/map-interactions.spec.ts: ~1420 km → ~10 s at scale 1000.
|
// Madrid–Barajas — same long leg as e2e/map-interactions.spec.ts: ~1420 km → ~10 s at scale 1000.
|
||||||
const DEST = 'LEMD';
|
const DEST = 'LEMD';
|
||||||
|
// Amsterdam — a third airport, distinct from hub and destination (the queued stop in the ISS-077 test).
|
||||||
|
const QUEUE = 'EHAM';
|
||||||
|
|
||||||
interface PlaneState {
|
interface PlaneState {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -79,6 +81,14 @@ async function createPackage(page: Page, fromIcao: string, toIcao: string): Prom
|
|||||||
return (await created.json()) as PackageState;
|
return (await created.json()) as PackageState;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Test hook (FLIGHT_TEST_HOOKS=1): top the starter's tank back to full — replaces the removed /refuel
|
||||||
|
// endpoint (ISS-082). Reads maxFuel from the snapshot so no catalog mirror is needed.
|
||||||
|
async function setFuelFull(page: Page, planeId: string): Promise<void> {
|
||||||
|
const s = await getState(page);
|
||||||
|
const p = s.planes.find((x) => x.id === planeId)!;
|
||||||
|
expect((await page.request.post('/api/test/set-fuel', { data: { planeId, fuel: p.maxFuel } })).status()).toBe(200);
|
||||||
|
}
|
||||||
|
|
||||||
// Self-heal: let any in-flight leg finish, then reposition plane-starter home via the API.
|
// Self-heal: let any in-flight leg finish, then reposition plane-starter home via the API.
|
||||||
async function flyHomeViaApi(page: Page): Promise<void> {
|
async function flyHomeViaApi(page: Page): Promise<void> {
|
||||||
const s0 = await getState(page);
|
const s0 = await getState(page);
|
||||||
@@ -443,9 +453,8 @@ test('hovering the fleet row of a flying plane highlights its route', async ({ p
|
|||||||
test.setTimeout(600_000); // self-heal + one flight at scale 1000 + fly-home cleanup
|
test.setTimeout(600_000); // self-heal + one flight at scale 1000 + fly-home cleanup
|
||||||
await flyHomeViaApi(page);
|
await flyHomeViaApi(page);
|
||||||
|
|
||||||
// Full tank before departure — the EDDF↔LEMD round trip burns ~4970 L of the 6300 L tank.
|
// Full tank before departure — deterministic baseline (ISS-082 hook; dispatch would auto-refuel anyway).
|
||||||
const refuel = await page.request.post('/api/planes/plane-starter/refuel');
|
await setFuelFull(page, 'plane-starter');
|
||||||
expect(refuel.status()).toBe(200);
|
|
||||||
|
|
||||||
await page.goto('/');
|
await page.goto('/');
|
||||||
await waitForAirportCount(page);
|
await waitForAirportCount(page);
|
||||||
@@ -500,55 +509,52 @@ test('hovering the fleet row of a flying plane highlights its route', async ({ p
|
|||||||
.toBe(true);
|
.toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('hovering an on-board package while its carrier is mid-flight traces from current position', async ({ page }) => {
|
test('hovering an on-board package while its carrier is mid-flight traces from the landing airport', async ({ page }) => {
|
||||||
test.setTimeout(600_000); // self-heal + one flight at scale 1000 + fly-home cleanup
|
test.setTimeout(600_000); // self-heal + one flight at scale 1000 + fly-home cleanup
|
||||||
await flyHomeViaApi(page);
|
await flyHomeViaApi(page);
|
||||||
|
|
||||||
// Full tank before departure — the EDDF↔LEMD round trip burns ~4970 L of the 6300 L tank.
|
// Full tank before departure — deterministic baseline (ISS-082 hook; dispatch would auto-refuel anyway).
|
||||||
const refuel = await page.request.post('/api/planes/plane-starter/refuel');
|
await setFuelFull(page, 'plane-starter');
|
||||||
expect(refuel.status()).toBe(200);
|
|
||||||
|
|
||||||
await page.goto('/');
|
await page.goto('/');
|
||||||
await waitForAirportCount(page);
|
await waitForAirportCount(page);
|
||||||
|
|
||||||
// Load + fly via the API (same pattern as e2e/map-interactions.spec.ts), then speed up.
|
// ISS-077 (v0.41.0): the package is destined for the QUEUED stop (EHAM), not the active leg's
|
||||||
const pkg = await createPackage(page, HUB, DEST);
|
// destination — load it, queue EHAM while grounded (pre-built routes are allowed), then start the
|
||||||
|
// HUB→DEST leg via the API (same pattern as e2e/map-interactions.spec.ts). The hover must trace
|
||||||
|
// from DEST (where this flight lands) to EHAM — NOT from the plane's live mid-flight position.
|
||||||
|
const pkg = await createPackage(page, HUB, QUEUE);
|
||||||
const load = await page.request.post(`/api/packages/${pkg.id}/load`, { data: { planeId: 'plane-starter' } });
|
const load = await page.request.post(`/api/packages/${pkg.id}/load`, { data: { planeId: 'plane-starter' } });
|
||||||
expect(load.status()).toBe(200);
|
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 fly = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: DEST } });
|
const fly = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: DEST } });
|
||||||
expect(fly.status()).toBe(200);
|
expect(fly.status()).toBe(200);
|
||||||
await setScale(page, SCALE);
|
// The endpoint's OWN post-action snapshot already shows the plane flying — no poll race.
|
||||||
|
const flyBody = (await fly.json()) as StateBody;
|
||||||
|
expect(flyBody.planes.find((p) => p.id === 'plane-starter')?.status).toBe('flying');
|
||||||
|
|
||||||
// Wait until the starter is GENUINELY mid-flight — its live position clearly away from EDDF in
|
// Freeze immediately: at a leftover scale of 1000 the ~10 s leg could otherwise land under us and
|
||||||
// both axes (well past HOVER_ROUTE_EPS_DEG) so "the trace starts at the plane" and "it starts at
|
// auto-chain the queued EHAM leg, which would change (or empty) the trace while we assert. Paused,
|
||||||
// the pickup airport" are distinguishable. The ~10 s leg at scale 1000 gives a wide window.
|
// every /api/state snapshot reports the same state — and the new rule's start point is the LANDING
|
||||||
const hubLonLat = await airportLonLat(page, HUB);
|
// airport regardless of progress, so no mid-flight position window is needed at all.
|
||||||
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 });
|
await postSim(page, { paused: true });
|
||||||
|
|
||||||
const row = page.locator(`[data-testid="onboard-package-${pkg.id}"]`);
|
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 });
|
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.
|
// Both trace endpoints must be in-viewport for queryRenderedFeatures to see them.
|
||||||
await fitToAirports(page, [HUB, DEST]);
|
await fitToAirports(page, [DEST, QUEUE]);
|
||||||
|
|
||||||
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);
|
const destLonLat = await airportLonLat(page, DEST);
|
||||||
|
const queueLonLat = await airportLonLat(page, QUEUE);
|
||||||
|
const hubLonLat = await airportLonLat(page, HUB);
|
||||||
|
|
||||||
await row.hover();
|
await row.hover();
|
||||||
// ISS-040 (v0.23.2): the trace starts at the carrier's LIVE position and ends at the destination,
|
// ISS-077 (v0.41.0): the trace starts at the LANDING airport (DEST) and ends at the package's
|
||||||
// and NO segment may start near the pickup airport (the old origin-based behavior). Same per-tile
|
// destination (the queued stop EHAM), and NO segment may start near the departure airport — that
|
||||||
// clipping/quantization caveats as expectHoverRoute — check endpoints across all segments with EPS.
|
// was the old live-position behavior right after takeoff. Same per-tile clipping/quantization
|
||||||
|
// caveats as expectHoverRoute — check endpoints across all segments with EPS.
|
||||||
await expect.poll(async () => {
|
await expect.poll(async () => {
|
||||||
const feats = (await renderedFeatures(page, ['hover-route'])) as Array<{ geometry?: { type: string; coordinates: [number, number][] } }>;
|
const feats = (await renderedFeatures(page, ['hover-route'])) as Array<{ geometry?: { type: string; coordinates: [number, number][] } }>;
|
||||||
const segs = feats.filter(
|
const segs = feats.filter(
|
||||||
@@ -558,11 +564,14 @@ test('hovering an on-board package while its carrier is mid-flight traces from c
|
|||||||
if (!segs.length) return false;
|
if (!segs.length) return false;
|
||||||
const near = (a: [number, number], b: [number, number]) =>
|
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;
|
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 startsAtDest = segs.some((f) => near(f.geometry.coordinates[0], destLonLat));
|
||||||
const endsAtDest = segs.some((f) => near(f.geometry.coordinates[f.geometry.coordinates.length - 1], destLonLat));
|
const endsAtQueue = segs.some((f) => {
|
||||||
|
const c = f.geometry.coordinates;
|
||||||
|
return near(c[c.length - 1], queueLonLat);
|
||||||
|
});
|
||||||
const noneStartsAtHub = !segs.some((f) => near(f.geometry.coordinates[0], hubLonLat));
|
const noneStartsAtHub = !segs.some((f) => near(f.geometry.coordinates[0], hubLonLat));
|
||||||
return startsAtLive && endsAtDest && noneStartsAtHub;
|
return startsAtDest && endsAtQueue && noneStartsAtHub;
|
||||||
}, { timeout: 15_000, message: 'waiting for the hover-route trace to run from the live position to the destination' }).toBe(true);
|
}, { timeout: 15_000, message: 'waiting for the hover-route trace to run from the landing airport (DEST) to the queued stop' }).toBe(true);
|
||||||
|
|
||||||
await unhover(page);
|
await unhover(page);
|
||||||
await expect.poll(async () => (await renderedFeatures(page, ['hover-route'])).length, {
|
await expect.poll(async () => (await renderedFeatures(page, ['hover-route'])).length, {
|
||||||
@@ -570,9 +579,12 @@ test('hovering an on-board package while its carrier is mid-flight traces from c
|
|||||||
message: 'waiting for the hover route trace to clear after mouseleave',
|
message: 'waiting for the hover route trace to clear after mouseleave',
|
||||||
}).toBe(0);
|
}).toBe(0);
|
||||||
|
|
||||||
// Resume and fast-forward to arrival — landing at DEST auto-delivers the package (v0.12.0), so
|
// Cleanup: cancel the queued leg first so landing at DEST is a plain grounding (no auto-chain),
|
||||||
// flying home afterwards leaves the starter clean for the other specs.
|
// resume + fast-forward to arrival, abandon the still-loaded package (it was destined for EHAM,
|
||||||
await postSim(page, { timeScale: SCALE, paused: false });
|
// not DEST — it never delivered), 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); // also clears the pause above
|
||||||
await expect
|
await expect
|
||||||
.poll(async () => {
|
.poll(async () => {
|
||||||
const p = (await getState(page)).planes.find((x) => x.id === 'plane-starter');
|
const p = (await getState(page)).planes.find((x) => x.id === 'plane-starter');
|
||||||
@@ -580,6 +592,9 @@ test('hovering an on-board package while its carrier is mid-flight traces from c
|
|||||||
}, { 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);
|
||||||
|
|
||||||
|
const abandon = await page.request.post(`/api/packages/${pkg.id}/abandon`);
|
||||||
|
expect(abandon.status()).toBe(200); // only possible once grounded — the poll above guarantees it
|
||||||
|
|
||||||
// ISS-041: the arrival above paused the sim, so re-set SCALE for this leg (setScale clears pause).
|
// ISS-041: the arrival above paused the sim, so re-set SCALE for this leg (setScale clears pause).
|
||||||
await setScale(page, SCALE);
|
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 } });
|
||||||
|
|||||||
@@ -0,0 +1,255 @@
|
|||||||
|
import type { Page } from '@playwright/test';
|
||||||
|
import { expect, test } from '@playwright/test';
|
||||||
|
// Real helpers (v0.39.0) — the broken-state burn math must match lib/ exactly; Playwright resolves
|
||||||
|
// the repo's tsconfig paths, so importing beats mirroring a third copy of the formulas.
|
||||||
|
import { initialBearingDeg } from '../lib/geo';
|
||||||
|
import { weatherFor } from '../lib/weather';
|
||||||
|
import { fuelAtWeighted, windBurnFactor } from '../lib/sim/movement';
|
||||||
|
// v0.39.0 (ISS-069) — maintenance: expectations use the real balance constants + burn helpers.
|
||||||
|
import { BROKEN_BURN_MULTIPLIER, REPAIR_COST } from '../lib/game/catalog';
|
||||||
|
|
||||||
|
// v0.39.0 (ISS-069) — maintenance visible flow against the live origin: health is shown per plane in
|
||||||
|
// the fleet list; forcing it to 0 via the set-health hook shows the "broken" pill and makes a short
|
||||||
|
// full-tank leg burn ×1.5 more fuel (asserted with the real lib helpers); clicking Repair deducts
|
||||||
|
// exactly REPAIR_COST, restores health and grounds the plane ("in repair" pill) until its gate
|
||||||
|
// passes; shortening the gate via the hook brings it back to service on the next tick.
|
||||||
|
|
||||||
|
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 STARTER = 'plane-starter';
|
||||||
|
|
||||||
|
interface PlaneState {
|
||||||
|
id: string;
|
||||||
|
model: string;
|
||||||
|
status: 'available' | 'flying' | 'repairing';
|
||||||
|
fuel: number;
|
||||||
|
maxFuel: number;
|
||||||
|
locationIcao: string;
|
||||||
|
destIcao: string | null;
|
||||||
|
health: number; // v0.39.0 (ISS-069) — structural health in [0, 100]
|
||||||
|
repairUntilSimTime: number | null; // v0.39.0 (ISS-069) — active repair gate
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CatalogEntry {
|
||||||
|
model: string;
|
||||||
|
burnPerKm: number;
|
||||||
|
emptyWeightKg: number;
|
||||||
|
maxFuel: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface StateBody {
|
||||||
|
account: { cash: number };
|
||||||
|
simState: { clockMs: number; timeScale: number; paused: boolean };
|
||||||
|
planes: PlaneState[];
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set the time scale and VERIFY from the response that it stuck — a silent reset would otherwise
|
||||||
|
// surface as an unexplained wait timeout. Also clears pause (ISS-041: landings slow to 1×).
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test hook (FLIGHT_TEST_HOOKS=1): force a plane's health and/or shorten an active repair gate.
|
||||||
|
async function setHealth(
|
||||||
|
page: Page,
|
||||||
|
body: { planeId: string; health?: number; repairUntilMs?: number },
|
||||||
|
): Promise<StateBody> {
|
||||||
|
const res = await page.request.post('/api/test/set-health', { data: body });
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
return (await res.json()) as StateBody;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test hook (FLIGHT_TEST_HOOKS=1): top a plane's tank back to full — replaces the removed /refuel
|
||||||
|
// endpoint (ISS-082). Reads maxFuel from the snapshot so no catalog mirror is needed.
|
||||||
|
async function setFuelFull(page: Page, planeId: string): Promise<void> {
|
||||||
|
const s = await getState(page);
|
||||||
|
const p = s.planes.find((x) => x.id === planeId)!;
|
||||||
|
expect((await page.request.post('/api/test/set-fuel', { data: { planeId, fuel: p.maxFuel } })).status()).toBe(200);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mirrors haversineKm in lib/geo.ts (same formula → identical floats).
|
||||||
|
function haversineKm(lat1: number, lon1: number, lat2: number, lon2: number): number {
|
||||||
|
const toRad = (d: number) => (d * Math.PI) / 180;
|
||||||
|
const dLat = toRad(lat2 - lat1);
|
||||||
|
const dLon = toRad(lon2 - lon1);
|
||||||
|
const a =
|
||||||
|
Math.sin(dLat / 2) ** 2 +
|
||||||
|
Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLon / 2) ** 2;
|
||||||
|
return 2 * 6371 * Math.asin(Math.min(1, Math.sqrt(a)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Closest airport to EDDF from /api/airports — the short fixed leg for the broken-burn flight.
|
||||||
|
// Returns both endpoints' coordinates so the exact-km fuel assertion can mirror lib/geo.ts.
|
||||||
|
async function nearestToHub(page: Page): 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 nearest = fc.features.filter((f) => f.properties.icao !== HUB)[0].properties;
|
||||||
|
for (const f of fc.features) {
|
||||||
|
if (f.properties.icao === HUB) continue;
|
||||||
|
if (haversineKm(hub.lat, hub.lon, f.properties.lat, f.properties.lon) < haversineKm(hub.lat, hub.lon, nearest.lat, nearest.lon)) {
|
||||||
|
nearest = f.properties;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { icao: nearest.icao, lat: nearest.lat, lon: nearest.lon, hubLat: hub.lat, hubLon: hub.lon };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Self-heal: let any in-flight leg finish and reposition plane-starter to the hub (shared DB — an
|
||||||
|
// interrupted earlier run may have left it elsewhere or airborne). Same pattern as flyHomeViaApi in
|
||||||
|
// right-pane.spec.ts; cargo cleanup is skipped because this flow asserts cash DELTAS, not absolutes.
|
||||||
|
async function healStarterHome(page: Page): Promise<void> {
|
||||||
|
let s = await getState(page);
|
||||||
|
let starter = s.planes.find((p) => p.id === STARTER)!;
|
||||||
|
if (starter.status === 'repairing') {
|
||||||
|
// An interrupted run may have left it mid-repair — shorten the gate so the next tick flips it back.
|
||||||
|
await setHealth(page, { planeId: STARTER, health: 100, repairUntilMs: 0 });
|
||||||
|
await expect
|
||||||
|
.poll(async () => ((await getState(page)).planes.find((p) => p.id === STARTER)?.status ?? ''), {
|
||||||
|
timeout: 30_000,
|
||||||
|
message: 'waiting for the shortened repair gate to flip plane-starter back',
|
||||||
|
})
|
||||||
|
.toBe('available');
|
||||||
|
s = await getState(page);
|
||||||
|
starter = s.planes.find((p) => p.id === STARTER)!;
|
||||||
|
}
|
||||||
|
if (starter.status === 'flying' || starter.locationIcao !== HUB) {
|
||||||
|
// Fast-forward any leftover leg / repositioning flight (~20 s real time worst case at 1000×).
|
||||||
|
await setScale(page, SCALE);
|
||||||
|
}
|
||||||
|
if (starter.status === 'flying') {
|
||||||
|
await expect
|
||||||
|
.poll(async () => ((await getState(page)).planes.find((p) => p.id === STARTER)?.status ?? ''), {
|
||||||
|
timeout: 240_000,
|
||||||
|
message: 'waiting for an in-flight plane-starter to land',
|
||||||
|
})
|
||||||
|
.toBe('available');
|
||||||
|
s = await getState(page);
|
||||||
|
starter = s.planes.find((p) => p.id === STARTER)!;
|
||||||
|
}
|
||||||
|
if (starter.locationIcao !== HUB) {
|
||||||
|
// ISS-041: the landing above slowed the sim to 1× — setScale restores it for the return leg.
|
||||||
|
await setScale(page, SCALE);
|
||||||
|
// ISS-082: dispatch auto-refuels, so a grounded plane can always start any full-tank-flyable
|
||||||
|
// leg when cash allows — no top-up retry needed.
|
||||||
|
const flyHome = await page.request.post(`/api/planes/${STARTER}/fly`, { data: { destIcao: HUB } });
|
||||||
|
expect(flyHome.status()).toBe(200); // repositioning needs no package (v0.12.0 manual flight)
|
||||||
|
await expect
|
||||||
|
.poll(async () => ((await getState(page)).planes.find((p) => p.id === STARTER)?.locationIcao ?? ''), {
|
||||||
|
timeout: 240_000,
|
||||||
|
message: 'waiting for plane-starter to land back at the hub',
|
||||||
|
})
|
||||||
|
.toBe(HUB);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Leave a clean starter for later spec files (shared DB, workers:1): full health and no active
|
||||||
|
// repair gate — an interrupted run may have left the plane mid-repair or worn down.
|
||||||
|
async function restoreStarter(page: Page): Promise<void> {
|
||||||
|
const s = await getState(page);
|
||||||
|
const starter = s.planes.find((p) => p.id === STARTER)!;
|
||||||
|
const body: { planeId: string; health?: number; repairUntilMs?: number } = { planeId: STARTER, health: 100 };
|
||||||
|
if (starter.status === 'repairing') body.repairUntilMs = 0; // shorten the active gate → flips on the next tick
|
||||||
|
await setHealth(page, body);
|
||||||
|
}
|
||||||
|
|
||||||
|
test.describe.configure({ mode: 'serial' }); // shared live DB — order matters within this file
|
||||||
|
|
||||||
|
// On exit (success or failure): restore scale=1 / unpaused for the other specs (house convention)
|
||||||
|
// and leave a clean starter — full health, no active repair gate.
|
||||||
|
test.afterEach(async ({ page }) => {
|
||||||
|
const res = await page.request.post('/api/sim', { data: { timeScale: 1, paused: false } });
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
await restoreStarter(page);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('health shown → broken burn ×1.5 → repair grounds for 3 sim days → back to service', async ({ page }) => {
|
||||||
|
test.setTimeout(300_000); // self-heal + one short leg at 1000× + the shortened repair gate wait
|
||||||
|
|
||||||
|
await healStarterHome(page); // deterministic: the starter sits grounded at EDDF
|
||||||
|
|
||||||
|
// (a) Force health to 42 — snapshot AND UI show it.
|
||||||
|
let s = await setHealth(page, { planeId: STARTER, health: 42 });
|
||||||
|
expect(s.planes.find((p) => p.id === STARTER)!.health).toBe(42);
|
||||||
|
|
||||||
|
await page.goto('/');
|
||||||
|
const row = page.getByTestId(`plane-${STARTER}`);
|
||||||
|
await expect(row, 'the starter fleet row renders').toBeVisible({ timeout: 15_000 });
|
||||||
|
await expect(page.getByTestId(`plane-health-${STARTER}`), 'health readout shows the forced value')
|
||||||
|
.toContainText('42%');
|
||||||
|
|
||||||
|
// (b) Force broken — the pill shows, and a short full-tank leg burns ×1.5 more fuel.
|
||||||
|
s = await setHealth(page, { planeId: STARTER, health: 0 });
|
||||||
|
expect(s.planes.find((p) => p.id === STARTER)!.health).toBe(0);
|
||||||
|
await expect(page.getByTestId(`plane-broken-${STARTER}`), 'the broken pill appears')
|
||||||
|
.toHaveText('broken', { timeout: 15_000 });
|
||||||
|
|
||||||
|
// Full tank for the flight (ISS-082 hook — dispatch would only top up to 150% of the leg, not full)…
|
||||||
|
await setFuelFull(page, STARTER);
|
||||||
|
s = await getState(page);
|
||||||
|
const starter = s.planes.find((p) => p.id === STARTER)!;
|
||||||
|
expect(starter.fuel).toBe(starter.maxFuel);
|
||||||
|
|
||||||
|
// …then fly the short fixed leg HUB → nearest via the API (the UI under test is maintenance, not dispatch).
|
||||||
|
const nearest = await nearestToHub(page);
|
||||||
|
expect((await page.request.post(`/api/planes/${STARTER}/fly`, { data: { destIcao: nearest.icao } })).status()).toBe(200);
|
||||||
|
await setScale(page, SCALE);
|
||||||
|
await expect
|
||||||
|
.poll(async () => ((await getState(page)).planes.find((p) => p.id === STARTER)?.locationIcao ?? ''), {
|
||||||
|
timeout: 120_000,
|
||||||
|
message: 'waiting for the broken plane to land at the nearest airport',
|
||||||
|
})
|
||||||
|
.toBe(nearest.icao);
|
||||||
|
|
||||||
|
// Landed fuel matches the ×1.5-adjusted closed form (real lib helpers — same pattern as right-pane.spec.ts).
|
||||||
|
s = await getState(page);
|
||||||
|
const landed = s.planes.find((p) => p.id === STARTER)!;
|
||||||
|
const entry = s.catalog.find((e) => e.model === starter.model)!;
|
||||||
|
const km = haversineKm(nearest.hubLat, nearest.hubLon, nearest.lat, nearest.lon);
|
||||||
|
const wHub = weatherFor(HUB);
|
||||||
|
const burn = entry.burnPerKm * windBurnFactor(wHub.windKt, wHub.windDirDeg, initialBearingDeg(nearest.hubLat, nearest.hubLon, nearest.lat, nearest.lon));
|
||||||
|
expect(landed.fuel).toBeCloseTo(fuelAtWeighted(starter.maxFuel, burn * BROKEN_BURN_MULTIPLIER, entry.emptyWeightKg, entry.maxFuel, km, 1), 6);
|
||||||
|
// Wear clamped at 0 — the broken plane stays broken.
|
||||||
|
expect(landed.health).toBe(0);
|
||||||
|
|
||||||
|
// (c) Repair through the UI: exact cash drop + "in repair" pill.
|
||||||
|
const cashBefore = s.account.cash;
|
||||||
|
const repairBtn = page.getByTestId(`repair-${STARTER}`);
|
||||||
|
await expect(repairBtn, 'the Repair button shows for a grounded worn plane').toBeVisible({ timeout: 15_000 });
|
||||||
|
// The click fires the POST asynchronously — capture the endpoint's OWN response so the cash drop is
|
||||||
|
// checked against the exact game clock the server used (a later GET would tick further).
|
||||||
|
const [res] = await Promise.all([
|
||||||
|
page.waitForResponse((r) => r.url().includes(`/api/planes/${STARTER}/repair`), { timeout: 15_000 }),
|
||||||
|
repairBtn.click(),
|
||||||
|
]);
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
const post = (await res.json()) as StateBody; // full post-action snapshot at the action's clock
|
||||||
|
expect(post.account.cash).toBeCloseTo(cashBefore - REPAIR_COST, 6); // exactly REPAIR_COST
|
||||||
|
const repaired = post.planes.find((p) => p.id === STARTER)!;
|
||||||
|
expect(repaired.status).toBe('repairing');
|
||||||
|
expect(repaired.health).toBe(100); // restored to full…
|
||||||
|
expect(repaired.repairUntilSimTime).not.toBeNull(); // …with the gate set (3 sim days out)
|
||||||
|
|
||||||
|
await expect(page.getByTestId(`plane-repairing-${STARTER}`), 'the "in repair" pill appears')
|
||||||
|
.toHaveText('in repair', { timeout: 15_000 });
|
||||||
|
|
||||||
|
// (d) Shorten the gate via the hook — the plane comes back to service on the next tick.
|
||||||
|
await setHealth(page, { planeId: STARTER, repairUntilMs: 10_000 });
|
||||||
|
await setScale(page, SCALE); // fast-forward the shortened gate (each tick advances up to 2 s × scale)
|
||||||
|
await expect
|
||||||
|
.poll(async () => {
|
||||||
|
const p = (await getState(page)).planes.find((x) => x.id === STARTER)!;
|
||||||
|
return p.status === 'available' && p.health === 100 ? true : false;
|
||||||
|
}, { timeout: 60_000, message: 'waiting for the shortened repair gate to flip the plane back' })
|
||||||
|
.toBe(true);
|
||||||
|
});
|
||||||
@@ -93,6 +93,14 @@ async function createPackage(page: Page, fromIcao: string, toIcao: string): Prom
|
|||||||
return (await created.json()) as PackageState;
|
return (await created.json()) as PackageState;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Test hook (FLIGHT_TEST_HOOKS=1): top the starter's tank back to full — replaces the removed /refuel
|
||||||
|
// endpoint (ISS-082). Reads maxFuel from the snapshot so no catalog mirror is needed.
|
||||||
|
async function setFuelFull(page: Page, planeId: string): Promise<void> {
|
||||||
|
const s = await getState(page);
|
||||||
|
const p = s.planes.find((x) => x.id === planeId)!;
|
||||||
|
expect((await page.request.post('/api/test/set-fuel', { data: { planeId, fuel: p.maxFuel } })).status()).toBe(200);
|
||||||
|
}
|
||||||
|
|
||||||
// Load a package onto plane-starter and fly it from → to via the API, then poll at
|
// Load a package onto plane-starter and fly it from → to via the API, then poll at
|
||||||
// scale 1000 until the plane lands at `to`. Same pattern as e2e/actions.spec.ts.
|
// scale 1000 until the plane lands at `to`. Same pattern as e2e/actions.spec.ts.
|
||||||
async function loadAndFly(page: Page, fromIcao: string, toIcao: string): Promise<PackageState> {
|
async function loadAndFly(page: Page, fromIcao: string, toIcao: string): Promise<PackageState> {
|
||||||
@@ -198,10 +206,8 @@ test('plane markers move while flying and the plane popup shows status + route',
|
|||||||
await loadAndFly(page, starterLoc, HUB);
|
await loadAndFly(page, starterLoc, HUB);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Full tank before departure — the EDDF↔LEMD round trip burns ~4970 L of the 6300 L tank,
|
// Full tank before departure — deterministic baseline (ISS-082 hook; dispatch would auto-refuel anyway).
|
||||||
// so a partially drained plane left by an earlier spec could not make it home.
|
await setFuelFull(page, 'plane-starter');
|
||||||
const refuel = await page.request.post('/api/planes/plane-starter/refuel');
|
|
||||||
expect(refuel.status()).toBe(200);
|
|
||||||
|
|
||||||
// 1) Load the hook-created package — a GROUNDED plane draws no route line yet.
|
// 1) Load the hook-created package — a GROUNDED plane draws no route line yet.
|
||||||
const pkg = await createPackage(page, HUB, DEST);
|
const pkg = await createPackage(page, HUB, DEST);
|
||||||
|
|||||||
@@ -33,6 +33,11 @@ test('header shows the app version sourced from package.json', async ({ page })
|
|||||||
await page.goto(APP_URL);
|
await page.goto(APP_URL);
|
||||||
const header = page.getByTestId('app-header');
|
const header = page.getByTestId('app-header');
|
||||||
await expect(header).toContainText(`v${pkg.version}`);
|
await expect(header).toContainText(`v${pkg.version}`);
|
||||||
|
// ISS-080 (v0.40.0): the version links to the repo's CHANGELOG.md.
|
||||||
|
await expect(page.getByTestId('app-version')).toHaveAttribute(
|
||||||
|
'href',
|
||||||
|
'https://git.kkhost.pl/OpenCode/Flight-Ops/src/branch/master/CHANGELOG.md',
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('clicking an airport marker opens a popup with name and ICAO', async ({ page }) => {
|
test('clicking an airport marker opens a popup with name and ICAO', async ({ page }) => {
|
||||||
|
|||||||
+3
-6
@@ -75,13 +75,10 @@ test('left pane renders wallet, reputation and the starter fleet at Frankfurt',
|
|||||||
await expect(page.getByTestId('left-pane').getByRole('heading', { name: 'On board', exact: true })).toHaveCount(0);
|
await expect(page.getByTestId('left-pane').getByRole('heading', { name: 'On board', exact: true })).toHaveCount(0);
|
||||||
await expect(page.getByTestId('right-pane').getByRole('heading', { name: 'On board', exact: true })).toHaveCount(0);
|
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
|
// ISS-082 (v0.42.0): manual refuel is gone — dispatch auto-refuels instead, so neither pane has a
|
||||||
// heading and button render here…
|
// Refuel heading or row anymore.
|
||||||
await expect(page.getByTestId('left-pane').getByRole('heading', { name: 'Refuel', exact: true })).toBeVisible();
|
await expect(page.getByTestId('left-pane').getByRole('heading', { name: 'Refuel', exact: true })).toHaveCount(0);
|
||||||
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').getByRole('heading', { name: 'Refuel', exact: true })).toHaveCount(0);
|
||||||
await expect(page.getByTestId('right-pane').getByTestId('market-refuel')).toHaveCount(0);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test('sim clock ticks smoothly between polls — seconds advance without waiting for a snapshot (ISS-007)', async ({ page }) => {
|
test('sim clock ticks smoothly between polls — seconds advance without waiting for a snapshot (ISS-007)', async ({ page }) => {
|
||||||
|
|||||||
+73
-9
@@ -15,6 +15,7 @@ const QUEUE = 'EHAM'; // Amsterdam — a third airport, distinct from hub and de
|
|||||||
interface PlaneState {
|
interface PlaneState {
|
||||||
id: string;
|
id: string;
|
||||||
status: 'available' | 'flying';
|
status: 'available' | 'flying';
|
||||||
|
maxFuel: number;
|
||||||
locationIcao: string;
|
locationIcao: string;
|
||||||
destIcao: string | null;
|
destIcao: string | null;
|
||||||
queue: string[];
|
queue: string[];
|
||||||
@@ -69,6 +70,14 @@ async function createPackage(page: Page, fromIcao: string, toIcao: string): Prom
|
|||||||
return (await created.json()) as PackageState;
|
return (await created.json()) as PackageState;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Test hook (FLIGHT_TEST_HOOKS=1): top the starter's tank back to full — replaces the removed /refuel
|
||||||
|
// endpoint (ISS-082). Reads maxFuel from the snapshot so no catalog mirror is needed.
|
||||||
|
async function setFuelFull(page: Page, planeId: string): Promise<void> {
|
||||||
|
const s = await getState(page);
|
||||||
|
const p = s.planes.find((x) => x.id === planeId)!;
|
||||||
|
expect((await page.request.post('/api/test/set-fuel', { data: { planeId, fuel: p.maxFuel } })).status()).toBe(200);
|
||||||
|
}
|
||||||
|
|
||||||
// Self-heal: let any in-flight leg finish, reposition plane-starter home via the API, and abandon
|
// 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.
|
// leftover cargo so every test starts from the canonical state even after an interrupted run.
|
||||||
async function flyHomeViaApi(page: Page): Promise<void> {
|
async function flyHomeViaApi(page: Page): Promise<void> {
|
||||||
@@ -201,9 +210,8 @@ 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
|
test.setTimeout(300_000); // self-heal can take minutes after an interrupted run
|
||||||
await flyHomeViaApi(page); // deterministic: the starter sits grounded at EDDF
|
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).
|
// Full tank before departure — deterministic baseline (ISS-082 hook; dispatch would auto-refuel anyway).
|
||||||
const refuel = await page.request.post('/api/planes/plane-starter/refuel');
|
await setFuelFull(page, 'plane-starter');
|
||||||
expect(refuel.status()).toBe(200);
|
|
||||||
|
|
||||||
const pkg = await createPackage(page, HUB, DEST);
|
const pkg = await createPackage(page, HUB, DEST);
|
||||||
|
|
||||||
@@ -272,9 +280,8 @@ test('dotted queue line renders the queued path on the map (ISS-043 part 2)', as
|
|||||||
test.setTimeout(300_000); // self-heal + one flight at scale 1000 + fly-home cleanup
|
test.setTimeout(300_000); // self-heal + one flight at scale 1000 + fly-home cleanup
|
||||||
await flyHomeViaApi(page);
|
await flyHomeViaApi(page);
|
||||||
|
|
||||||
// Full tank before departure — keeps the state canonical for whatever the cleanup does.
|
// Full tank before departure — keeps the state canonical for whatever the cleanup does (ISS-082 hook).
|
||||||
const refuel = await page.request.post('/api/planes/plane-starter/refuel');
|
await setFuelFull(page, 'plane-starter');
|
||||||
expect(refuel.status()).toBe(200);
|
|
||||||
|
|
||||||
// Load + queue + fly via the API: a package EDDF→LEMD, one queued leg LEMD→EHAM (works while
|
// 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].
|
// grounded — part 1), then start leg 1. The dotted line must show ONLY dest → queue[0].
|
||||||
@@ -350,13 +357,70 @@ test('dotted queue line renders the queued path on the map (ISS-043 part 2)', as
|
|||||||
}).toBe(HUB);
|
}).toBe(HUB);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('grounded plane with a pre-built queue draws its dotted route from its airport (ISS-077)', async ({ page }) => {
|
||||||
|
test.setTimeout(300_000); // self-heal + map assertions only — no flight in this test
|
||||||
|
await flyHomeViaApi(page); // deterministic: the starter sits grounded at EDDF
|
||||||
|
|
||||||
|
await page.goto('/');
|
||||||
|
await waitForAirportCount(page);
|
||||||
|
|
||||||
|
// Pre-build a two-leg route while GROUNDED via the raw API (queuing is allowed from any state,
|
||||||
|
// ISS-043 part 1) — no package or flight needed. The dotted line must chain HUB → DEST → QUEUE.
|
||||||
|
const q1 = await page.request.post('/api/planes/plane-starter/queue', { data: { destIcao: DEST } });
|
||||||
|
expect(q1.status()).toBe(200);
|
||||||
|
const q2 = await page.request.post('/api/planes/plane-starter/queue', { data: { destIcao: QUEUE } });
|
||||||
|
expect(q2.status()).toBe(200);
|
||||||
|
|
||||||
|
// All chain endpoints must be in-viewport for queryRenderedFeatures to see them.
|
||||||
|
await fitToAirports(page, [HUB, DEST, QUEUE]);
|
||||||
|
|
||||||
|
const hubLL = await airportLonLat(page, HUB);
|
||||||
|
const destLL = await airportLonLat(page, DEST);
|
||||||
|
const queueLL = await airportLonLat(page, QUEUE);
|
||||||
|
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. "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 chain HUB → DEST → QUEUE may be clipped into per-tile segments — check across all of them:
|
||||||
|
// some segment STARTS within EPS of the hub (the plane's airport, NOT a flight destination)…
|
||||||
|
const startsAtHub = segs.some((f) => near(f.geometry.coordinates[0], hubLL));
|
||||||
|
// …some ENDS within EPS of the last queued airport…
|
||||||
|
const endsAtQueue = segs.some((f) => {
|
||||||
|
const c = f.geometry.coordinates;
|
||||||
|
return near(c[c.length - 1], queueLL);
|
||||||
|
});
|
||||||
|
// …and the chain passes THROUGH the first queued airport — an interior joint point survives in
|
||||||
|
// whichever tile contains it (not guaranteed to be a segment endpoint after clipping).
|
||||||
|
const passesThroughDest = segs.some((f) => f.geometry.coordinates.some((c) => near(c, destLL)));
|
||||||
|
// Every rendered feature belongs to plane-starter.
|
||||||
|
const ownedByStarter = feats.every((f) => f.properties?.planeId === 'plane-starter');
|
||||||
|
return startsAtHub && endsAtQueue && passesThroughDest && ownedByStarter;
|
||||||
|
}, { timeout: 15_000, message: `waiting for the dotted queue line ${HUB} → ${DEST} → ${QUEUE}` }).toBe(true);
|
||||||
|
|
||||||
|
// Cleanup: cancel both queued legs (index 0 twice — each cancel shifts the rest down) so the
|
||||||
|
// starter stays grounded at HUB with an empty queue. No flight happened, nothing else to reset.
|
||||||
|
const c1 = await page.request.post('/api/planes/plane-starter/queue/cancel', { data: { index: 0 } });
|
||||||
|
expect(c1.status()).toBe(200);
|
||||||
|
const c2 = await page.request.post('/api/planes/plane-starter/queue/cancel', { data: { index: 0 } });
|
||||||
|
expect(c2.status()).toBe(200);
|
||||||
|
});
|
||||||
|
|
||||||
test('landing auto-starts the next queued leg (ISS-043 chain end-to-end)', async ({ page }) => {
|
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
|
test.setTimeout(300_000); // self-heal + two chained legs at scale 1000
|
||||||
await flyHomeViaApi(page);
|
await flyHomeViaApi(page);
|
||||||
|
|
||||||
// Full tank so fuel covers the chained return leg (same feasibility rule as /fly).
|
// Full tank for a deterministic baseline — the engine auto-chains (and auto-refuels, ISS-082) the return leg regardless.
|
||||||
const refuel = await page.request.post('/api/planes/plane-starter/refuel');
|
await setFuelFull(page, 'plane-starter');
|
||||||
expect(refuel.status()).toBe(200);
|
|
||||||
|
|
||||||
// Package EDDF→LEMD + a queued return leg LEMD→EDDF, then start leg 1.
|
// Package EDDF→LEMD + a queued return leg LEMD→EDDF, then start leg 1.
|
||||||
const pkg = await createPackage(page, HUB, DEST);
|
const pkg = await createPackage(page, HUB, DEST);
|
||||||
|
|||||||
+13
-7
@@ -15,7 +15,7 @@ const HUB = 'EDDF'; // Frankfurt Main — the seeded starter plane's home base (
|
|||||||
const POPUP_AIRPORT = { icao: 'LFRS', lon: -1.61073, lat: 47.153198 };
|
const POPUP_AIRPORT = { icao: 'LFRS', lon: -1.61073, lat: 47.153198 };
|
||||||
|
|
||||||
interface StateBody {
|
interface StateBody {
|
||||||
planes: Array<{ id: string; status: string; locationIcao: string; destIcao: string | null }>;
|
planes: Array<{ id: string; status: string; maxFuel: number; locationIcao: string; destIcao: string | null }>;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getState(page: Page): Promise<StateBody> {
|
async function getState(page: Page): Promise<StateBody> {
|
||||||
@@ -24,6 +24,14 @@ async function getState(page: Page): Promise<StateBody> {
|
|||||||
return (await res.json()) as StateBody;
|
return (await res.json()) as StateBody;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Test hook (FLIGHT_TEST_HOOKS=1): top the starter's tank back to full — replaces the removed /refuel
|
||||||
|
// endpoint (ISS-082). Reads maxFuel from the snapshot so no catalog mirror is needed.
|
||||||
|
async function setFuelFull(page: Page, planeId: string): Promise<void> {
|
||||||
|
const s = await getState(page);
|
||||||
|
const p = s.planes.find((x) => x.id === planeId)!;
|
||||||
|
expect((await page.request.post('/api/test/set-fuel', { data: { planeId, fuel: p.maxFuel } })).status()).toBe(200);
|
||||||
|
}
|
||||||
|
|
||||||
async function postSim(page: Page, body: Record<string, unknown>): Promise<void> {
|
async function postSim(page: Page, body: Record<string, unknown>): Promise<void> {
|
||||||
const res = await page.request.post('/api/sim', { data: body });
|
const res = await page.request.post('/api/sim', { data: body });
|
||||||
expect(res.ok()).toBeTruthy();
|
expect(res.ok()).toBeTruthy();
|
||||||
@@ -96,10 +104,8 @@ 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
|
test.setTimeout(300_000); // self-heal (worst case ~20 s at 1000×) + one short leg
|
||||||
await flyHomeViaApi(page);
|
await flyHomeViaApi(page);
|
||||||
|
|
||||||
// Full tank before departure — a partially drained plane left by an earlier spec could not
|
// Full tank before departure — deterministic baseline (ISS-082 hook; dispatch would auto-refuel anyway).
|
||||||
// afford the cleanup round trip.
|
await setFuelFull(page, 'plane-starter');
|
||||||
const refuel = await page.request.post('/api/planes/plane-starter/refuel');
|
|
||||||
expect(refuel.ok()).toBeTruthy();
|
|
||||||
|
|
||||||
const nearest = await nearestToHub(page);
|
const nearest = await nearestToHub(page);
|
||||||
|
|
||||||
@@ -130,8 +136,8 @@ 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
|
test.setTimeout(300_000); // self-heal (worst case ~20 s at 1000×) + one leg to LFRS
|
||||||
await flyHomeViaApi(page);
|
await flyHomeViaApi(page);
|
||||||
|
|
||||||
const refuel = await page.request.post('/api/planes/plane-starter/refuel');
|
// Full tank before departure — deterministic baseline (ISS-082 hook; dispatch would auto-refuel anyway).
|
||||||
expect(refuel.ok()).toBeTruthy();
|
await setFuelFull(page, 'plane-starter');
|
||||||
|
|
||||||
await page.goto('/');
|
await page.goto('/');
|
||||||
|
|
||||||
|
|||||||
+66
-132
@@ -4,9 +4,9 @@ import { expect, test } from '@playwright/test';
|
|||||||
// the repo's tsconfig paths, so importing beats mirroring a third copy of the formulas.
|
// the repo's tsconfig paths, so importing beats mirroring a third copy of the formulas.
|
||||||
import { initialBearingDeg } from '../lib/geo';
|
import { initialBearingDeg } from '../lib/geo';
|
||||||
import { weatherFor } from '../lib/weather';
|
import { weatherFor } from '../lib/weather';
|
||||||
import { windBurnFactor } from '../lib/sim/movement';
|
import { fuelAtWeighted, windBurnFactor } from '../lib/sim/movement';
|
||||||
// v0.38.0 (ISS-072) — reputation discounts: expectations computed from the LIVE snapshot's rep with the real helpers.
|
// v0.38.0 (ISS-072) — reputation discounts: expectations computed from the LIVE snapshot's rep with the real helpers.
|
||||||
import { FUEL_DISCOUNT_PER_REP, MAX_FUEL_DISCOUNT, MAX_PLANE_DISCOUNT, PLANE_DISCOUNT_PER_REP, repRate } from '../lib/game/catalog';
|
import { conditionBurnMultiplier, FUEL_DISCOUNT_PER_REP, MAX_FUEL_DISCOUNT, MAX_PLANE_DISCOUNT, PLANE_DISCOUNT_PER_REP, repRate } from '../lib/game/catalog';
|
||||||
import { STARTING_REPUTATION } from '../lib/game/seed';
|
import { STARTING_REPUTATION } from '../lib/game/seed';
|
||||||
|
|
||||||
// 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
|
||||||
@@ -14,8 +14,8 @@ import { STARTING_REPUTATION } from '../lib/game/seed';
|
|||||||
// (moved to the left pane in v0.20.0, ISS-021) shows loaded packages with fly-to-destination +
|
// (moved to the left pane in v0.20.0, ISS-021) shows loaded packages with fly-to-destination +
|
||||||
// abandon buttons (penalty preview from the same
|
// abandon buttons (penalty preview from the same
|
||||||
// formula as the server); flying planes show their current leg; market buy/sell previews match
|
// 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
|
// the catalog + economy constants exposed in /api/state, and dispatch auto-refuels a low tank to
|
||||||
// left pane in v0.23.0, ISS-035) deducts exactly its cost. Packages are created via
|
// 150% of the leg requirement at exactly its rep-discounted cost (ISS-082). 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
|
||||||
@@ -27,6 +27,7 @@ interface PlaneState {
|
|||||||
status: 'available' | 'flying';
|
status: 'available' | 'flying';
|
||||||
fuel: number;
|
fuel: number;
|
||||||
maxFuel: number;
|
maxFuel: number;
|
||||||
|
health: number; // v0.39.0 (ISS-069) — feeds conditionBurnMultiplier in the auto-refuel math
|
||||||
locationIcao: string;
|
locationIcao: string;
|
||||||
destIcao: string | null;
|
destIcao: string | null;
|
||||||
}
|
}
|
||||||
@@ -112,7 +113,8 @@ function penaltyFor(reward: number, createdSimTime: number, deadlineSimTime: num
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Closest airport to EDDF from /api/airports → shortest possible arrival time at scale 1000.
|
// Closest airport to EDDF from /api/airports → shortest possible arrival time at scale 1000.
|
||||||
async function nearestToHub(page: Page): Promise<{ icao: string; lat: number; lon: number }> {
|
// Returns both endpoints' coordinates so exact-km fuel assertions can mirror lib/geo.ts.
|
||||||
|
async function nearestToHub(page: Page): Promise<{ icao: string; lat: number; lon: number; hubLat: number; hubLon: number }> {
|
||||||
const fc = (await (await page.request.get('/api/airports')).json()) as {
|
const fc = (await (await page.request.get('/api/airports')).json()) as {
|
||||||
features: Array<{ properties: { icao: string; lat: number; lon: number } }>;
|
features: Array<{ properties: { icao: string; lat: number; lon: number } }>;
|
||||||
};
|
};
|
||||||
@@ -124,38 +126,7 @@ async function nearestToHub(page: Page): Promise<{ icao: string; lat: number; lo
|
|||||||
nearest = f.properties;
|
nearest = f.properties;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nearest;
|
return { ...nearest, hubLat: hub.lat, hubLon: hub.lon };
|
||||||
}
|
|
||||||
|
|
||||||
// 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, so a
|
|
||||||
// full-tank fly there would rightly 409; this test wants a long-but-flyable leg instead. Wind-
|
|
||||||
// adjusted (v0.36.0): BOTH directions must fit — the outbound is flown from a full tank and the
|
|
||||||
// return leg is what the forFlight refuel below buys, which also 409s if it doesn't fit.
|
|
||||||
async function farthestFlyableToHub(
|
|
||||||
page: Page,
|
|
||||||
entry: CatalogEntry,
|
|
||||||
): Promise<{ icao: string; lat: number; lon: number; d: 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;
|
|
||||||
const wHub = weatherFor(HUB);
|
|
||||||
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);
|
|
||||||
const wDest = weatherFor(f.properties.icao);
|
|
||||||
const outBurn = entry.burnPerKm * windBurnFactor(wHub.windKt, wHub.windDirDeg, initialBearingDeg(hub.lat, hub.lon, f.properties.lat, f.properties.lon));
|
|
||||||
if (requiredFuelFor(outBurn, entry.emptyWeightKg, entry.maxFuel, d) > entry.maxFuel) continue; // beyond range
|
|
||||||
const backBurn = entry.burnPerKm * windBurnFactor(wDest.windKt, wDest.windDirDeg, initialBearingDeg(f.properties.lat, f.properties.lon, hub.lat, hub.lon));
|
|
||||||
if (requiredFuelFor(backBurn, entry.emptyWeightKg, entry.maxFuel, d) > entry.maxFuel) continue; // return leg wouldn't fit a full tank either
|
|
||||||
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 —
|
// Mirrors lib/sim/movement.ts (v0.16.0): fuel required to cover distanceKm arriving empty —
|
||||||
@@ -184,7 +155,11 @@ async function createPackage(page: Page, fromIcao: string, toIcao: string, deadl
|
|||||||
|
|
||||||
// Self-heal: let any in-flight leg finish, then reposition plane-starter home via the API.
|
// Self-heal: let any in-flight leg finish, then reposition plane-starter home via the API.
|
||||||
async function flyHomeViaApi(page: Page): Promise<void> {
|
async function flyHomeViaApi(page: Page): Promise<void> {
|
||||||
const s0 = await getState(page);
|
// v0.39.0 (ISS-069): wear accumulates across the shared CI DB — restore full health and clear any
|
||||||
|
// active repair gate from an interrupted run before the steps below act on the starter, so the
|
||||||
|
// farthest-flyable picker and fuel pins never see a worn or broken plane.
|
||||||
|
expect((await page.request.post('/api/test/set-health', { data: { planeId: 'plane-starter', health: 100, repairUntilMs: 0 } })).status()).toBe(200);
|
||||||
|
const s0 = await getState(page); // ticks — a shortened gate flips the plane back to available here
|
||||||
const starter = s0.planes.find((p) => p.id === 'plane-starter')!;
|
const starter = s0.planes.find((p) => p.id === 'plane-starter')!;
|
||||||
if (starter.status === 'flying' || starter.locationIcao !== HUB) {
|
if (starter.status === 'flying' || starter.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×).
|
||||||
@@ -200,14 +175,10 @@ async function flyHomeViaApi(page: Page): Promise<void> {
|
|||||||
}
|
}
|
||||||
if (starter.locationIcao !== HUB) {
|
if (starter.locationIcao !== HUB) {
|
||||||
// ISS-041: the landing above paused the sim — setScale clears pause so the return leg
|
// ISS-041: the landing above paused the sim — setScale clears pause so the return leg
|
||||||
// fast-forwards instead of taking real-time hours.
|
// fast-forwards instead of taking real-time hours. ISS-082: dispatch auto-refuels, so a
|
||||||
|
// grounded plane can always start any full-tank-flyable leg when cash allows — no top-up retry needed.
|
||||||
await setScale(page, SCALE);
|
await setScale(page, SCALE);
|
||||||
let flyHome = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
const flyHome = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||||
if (!flyHome.ok()) {
|
|
||||||
// A long outbound leg can leave the tank too empty for the return — top up and retry.
|
|
||||||
expect((await page.request.post('/api/planes/plane-starter/refuel')).status()).toBe(200);
|
|
||||||
flyHome = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
|
||||||
}
|
|
||||||
expect(flyHome.status()).toBe(200); // repositioning needs no package (v0.12.0 manual flight)
|
expect(flyHome.status()).toBe(200); // repositioning needs no package (v0.12.0 manual flight)
|
||||||
await expect
|
await expect
|
||||||
.poll(async () => (await getState(page)).planes.find((p) => p.id === 'plane-starter')?.locationIcao === HUB, {
|
.poll(async () => (await getState(page)).planes.find((p) => p.id === 'plane-starter')?.locationIcao === HUB, {
|
||||||
@@ -357,7 +328,7 @@ test('on-board list: fly-to-destination + abandon with penalty preview; flying p
|
|||||||
.toBe(true);
|
.toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('market buy/sell render with previews from the catalog in /api/state; left-pane Refuel deducts exactly', async ({ page }) => {
|
test('market buy/sell render with previews from the catalog in /api/state', 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)
|
||||||
|
|
||||||
@@ -393,117 +364,80 @@ test('market buy/sell render with previews from the catalog in /api/state; left-
|
|||||||
await page.getByTestId('market-sell-plane').selectOption('plane-starter', { timeout: 15_000 });
|
await page.getByTestId('market-sell-plane').selectOption('plane-starter', { timeout: 15_000 });
|
||||||
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…
|
|
||||||
if (starter.fuel < starter.maxFuel) {
|
|
||||||
// v0.38.0 (ISS-072): rep-scaled cost — same formula as the server's refuelPlane 'full'.
|
|
||||||
const fuelRate = repRate(body.account.reputation, FUEL_DISCOUNT_PER_REP, MAX_FUEL_DISCOUNT);
|
|
||||||
const expectedCost = Math.round((starter.maxFuel - starter.fuel) * body.fuelPricePerL * (1 - fuelRate) * 100) / 100;
|
|
||||||
const cashBefore = body.account.cash;
|
|
||||||
|
|
||||||
// …the refuel picker lists it, the preview matches the exact cost, and the click deducts it.
|
|
||||||
await expect(page.getByTestId('market-refuel-plane')).toBeVisible({ timeout: 15_000 });
|
|
||||||
await page.getByTestId('market-refuel-plane').selectOption('plane-starter');
|
|
||||||
await expect(page.getByTestId('market-refuel-cost')).toContainText(eur(expectedCost));
|
|
||||||
await page.getByTestId('market-refuel').click();
|
|
||||||
|
|
||||||
// Cash decreased by exactly the expected cost and the tank is full (server truth).
|
|
||||||
await expect
|
|
||||||
.poll(async () => {
|
|
||||||
const b = await getState(page);
|
|
||||||
return Math.abs(b.account.cash - (cashBefore - expectedCost)) < 0.001;
|
|
||||||
}, { timeout: 15_000, message: 'waiting for the refuel cost to land in /api/state' })
|
|
||||||
.toBe(true);
|
|
||||||
const after = await getState(page);
|
|
||||||
expect(after.planes.find((p) => p.id === 'plane-starter')!.fuel).toBe(starter.maxFuel);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test('on-board row Refuel buys 150% of the weather-adjusted leg requirement; left-pane button says "Refuel to full"', async ({ page }) => {
|
// ISS-082 (v0.42.0): manual refuel is gone — dispatch auto-refuels instead. This test pins the new
|
||||||
test.setTimeout(300_000); // self-heal + one long flight each way at scale 1000
|
// behavior end-to-end: drop a grounded starter to low fuel via the hook, fly a leg, and assert the
|
||||||
|
// cash delta equals the EXACT rep-discounted top-up cost (computed from the snapshot + real lib
|
||||||
|
// helpers) while the post-flight landed fuel matches the weighted burn from the topped start value.
|
||||||
|
test('dispatch auto-refuels: a low tank tops up to 150% of the leg requirement and deducts exactly', async ({ page }) => {
|
||||||
|
test.setTimeout(300_000); // self-heal + one short flight each way at scale 1000
|
||||||
await flyHomeViaApi(page);
|
await flyHomeViaApi(page);
|
||||||
|
|
||||||
const body = await getState(page);
|
const body = await getState(page);
|
||||||
const entry = body.catalog.find((e) => e.model === 'atr72')!;
|
const entry = body.catalog.find((e) => e.model === 'atr72')!;
|
||||||
|
|
||||||
// Deterministic baseline: a full tank.
|
// Drop the grounded starter to a low, deterministic fuel level via the test hook — well below the
|
||||||
expect((await page.request.post('/api/planes/plane-starter/refuel')).status()).toBe(200);
|
// 150%-of-requirement target even for the shortest dataset leg (EDFH, ~93 km), so a top-up is guaranteed.
|
||||||
|
const LOW_FUEL = 50;
|
||||||
|
expect((await page.request.post('/api/test/set-fuel', { data: { planeId: 'plane-starter', fuel: LOW_FUEL } })).status()).toBe(200);
|
||||||
|
|
||||||
// Longest FLYABLE leg from the hub (fits a full tank) — long enough that 150% of its requirement
|
// Nearest airport to the hub → short leg, fast at scale 1000.
|
||||||
// exceeds what's left on arrival.
|
const nearest = await nearestToHub(page);
|
||||||
const farthest = await farthestFlyableToHub(page, entry);
|
const pre = await getState(page);
|
||||||
const pkg1 = await createPackage(page, HUB, farthest.icao, 24 * 3_600_000);
|
const starter = pre.planes.find((p) => p.id === 'plane-starter')!;
|
||||||
expect((await page.request.post(`/api/packages/${pkg1.id}/load`, { data: { planeId: 'plane-starter' } })).status()).toBe(200);
|
expect(starter.fuel).toBe(LOW_FUEL); // the hook stuck
|
||||||
|
|
||||||
// Fly there (delivers pkg1 on arrival) — the tank is now partial.
|
// Expected top-up from the snapshot constants — mirrors flyPlane's math (lib/game/actions.ts):
|
||||||
expect((await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: farthest.icao } })).status()).toBe(200);
|
// wind-adjusted requirement × condition multiplier, 150% margin capped at tank capacity.
|
||||||
|
const km = haversineKm(nearest.hubLat, nearest.hubLon, nearest.lat, nearest.lon);
|
||||||
|
const wHub = weatherFor(HUB);
|
||||||
|
const required = requiredFuelFor(
|
||||||
|
entry.burnPerKm * windBurnFactor(wHub.windKt, wHub.windDirDeg, initialBearingDeg(nearest.hubLat, nearest.hubLon, nearest.lat, nearest.lon)) * conditionBurnMultiplier(starter.health),
|
||||||
|
entry.emptyWeightKg,
|
||||||
|
entry.maxFuel,
|
||||||
|
km,
|
||||||
|
);
|
||||||
|
const target = Math.min(entry.maxFuel, Math.max(LOW_FUEL, required * 1.5)); // ISS-082: 150% margin, capped at tank capacity
|
||||||
|
const liters = Math.max(0, target - LOW_FUEL);
|
||||||
|
expect(liters).toBeGreaterThan(0); // the low tank genuinely needs a top-up
|
||||||
|
const fuelRate = repRate(pre.account.reputation, FUEL_DISCOUNT_PER_REP, MAX_FUEL_DISCOUNT);
|
||||||
|
const expectedCost = Math.round(liters * pre.fuelPricePerL * (1 - fuelRate) * 100) / 100;
|
||||||
|
const cashBefore = pre.account.cash;
|
||||||
|
|
||||||
|
// Dispatch via the API — the response snapshot is authoritative at the action's clock.
|
||||||
|
const flyRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: nearest.icao } });
|
||||||
|
expect(flyRes.status()).toBe(200); // auto-refuel made the low tank flyable…
|
||||||
|
const post = (await flyRes.json()) as StateBody;
|
||||||
|
expect(post.planes.find((p) => p.id === 'plane-starter')!.fuel).toBeCloseTo(target, 6); // …departing with exactly the topped level
|
||||||
|
expect(post.account.cash).toBeCloseTo(cashBefore - expectedCost, 6); // …at exactly the rep-discounted cost
|
||||||
|
|
||||||
|
// Fast-forward to arrival; the landed fuel is the weighted burn from the TOPPED start value.
|
||||||
await setScale(page, SCALE);
|
await setScale(page, SCALE);
|
||||||
await expect
|
await expect
|
||||||
.poll(async () => {
|
.poll(async () => {
|
||||||
const b = await getState(page);
|
const b = await getState(page);
|
||||||
const p = b.planes.find((x) => x.id === 'plane-starter');
|
const p = b.planes.find((x) => x.id === 'plane-starter');
|
||||||
return !!p && p.status === 'available' && p.locationIcao === farthest.icao;
|
return !!p && p.status === 'available' && p.locationIcao === nearest.icao;
|
||||||
}, { timeout: 240_000, message: `waiting for arrival at ${farthest.icao} (scale 1000)` })
|
}, { timeout: 120_000, message: `waiting for arrival at ${nearest.icao} (scale 1000)` })
|
||||||
.toBe(true);
|
.toBe(true);
|
||||||
|
|
||||||
// New work at the far end: a package back to the hub — its leg is exactly what we refuel for.
|
const landed = await getState(page);
|
||||||
const pkg2 = await createPackage(page, farthest.icao, HUB, 24 * 3_600_000);
|
expect(landed.planes.find((p) => p.id === 'plane-starter')!.fuel).toBeCloseTo(
|
||||||
expect((await page.request.post(`/api/packages/${pkg2.id}/load`, { data: { planeId: 'plane-starter' } })).status()).toBe(200);
|
fuelAtWeighted(target, entry.burnPerKm * windBurnFactor(wHub.windKt, wHub.windDirDeg, initialBearingDeg(nearest.hubLat, nearest.hubLon, nearest.lat, nearest.lon)) * conditionBurnMultiplier(starter.health), entry.emptyWeightKg, entry.maxFuel, km, 1),
|
||||||
|
6,
|
||||||
// Expected "150% of the requirement" from the snapshot constants (mirrors requiredFuelFor in
|
|
||||||
// lib/sim/movement.ts, wind-adjusted per v0.36.0 — departure weather at the far end vs heading home).
|
|
||||||
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 wFar = weatherFor(farthest.icao);
|
|
||||||
const required = requiredFuelFor(
|
|
||||||
entry.burnPerKm * windBurnFactor(wFar.windKt, wFar.windDirDeg, initialBearingDeg(farthest.lat, farthest.lon, farthest.hubLat, farthest.hubLon)),
|
|
||||||
entry.emptyWeightKg,
|
|
||||||
entry.maxFuel,
|
|
||||||
km,
|
|
||||||
);
|
);
|
||||||
const target = Math.min(entry.maxFuel, required * 1.5); // ISS-071: 150% margin, capped at tank capacity
|
|
||||||
const liters = Math.max(0, target - fuelBefore);
|
|
||||||
expect(liters).toBeGreaterThan(0); // the long leg genuinely needs more than what's left
|
|
||||||
// v0.38.0 (ISS-072): rep-scaled cost — same formula as the server's refuelPlane 'forFlight'.
|
|
||||||
const fuelRate = repRate(pre.account.reputation, FUEL_DISCOUNT_PER_REP, MAX_FUEL_DISCOUNT);
|
|
||||||
const expectedCost = Math.round(liters * pre.fuelPricePerL * (1 - fuelRate) * 100) / 100;
|
|
||||||
|
|
||||||
await page.goto('/');
|
// Restore: fly home (auto-refuel covers the return leg) and top the tank back up for later specs.
|
||||||
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
|
|
||||||
// 150% of the leg requirement (or a full tank), so the return is comfortably feasible. ISS-041:
|
|
||||||
// the far-end arrival above paused the sim, so re-set SCALE for this leg (setScale clears pause).
|
|
||||||
await setScale(page, SCALE);
|
await setScale(page, SCALE);
|
||||||
expect((await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } })).status()).toBe(200);
|
expect((await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } })).status()).toBe(200);
|
||||||
await expect
|
await expect
|
||||||
.poll(async () => (await getState(page)).planes.find((p) => p.id === 'plane-starter')?.locationIcao === HUB, {
|
.poll(async () => (await getState(page)).planes.find((p) => p.id === 'plane-starter')?.locationIcao === HUB, {
|
||||||
timeout: 240_000,
|
timeout: 120_000,
|
||||||
message: 'waiting for plane-starter to land back at the hub',
|
message: 'waiting for plane-starter to land back at the hub',
|
||||||
})
|
})
|
||||||
.toBe(true);
|
.toBe(true);
|
||||||
// Top the tank back up so later specs start with a full tank.
|
expect((await page.request.post('/api/test/set-fuel', { data: { planeId: 'plane-starter', fuel: entry.maxFuel } })).status()).toBe(200);
|
||||||
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('Ignore removes an open job from the list permanently (ISS-047 part B)', async ({ page }) => {
|
||||||
|
|||||||
@@ -80,12 +80,9 @@ async function flyHomeViaApi(page: Page): Promise<void> {
|
|||||||
// ISS-057: the landing above slowed the sim to 1× — setScale restores 1000× (and records it as
|
// 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.
|
// lastSelectedTimeScale) so the return leg fast-forwards instead of taking real-time hours.
|
||||||
await setScale(page, SCALE);
|
await setScale(page, SCALE);
|
||||||
let flyHome = await page.request.post(`/api/planes/${plane.id}/fly`, { data: { destIcao: HUB } });
|
// ISS-082: dispatch auto-refuels, so a grounded plane can always start any full-tank-flyable
|
||||||
if (!flyHome.ok()) {
|
// leg when cash allows — no top-up retry needed.
|
||||||
// A long outbound leg can leave the tank too empty for the return — top up and retry.
|
const flyHome = await page.request.post(`/api/planes/${plane.id}/fly`, { data: { destIcao: HUB } });
|
||||||
expect((await page.request.post(`/api/planes/${plane.id}/refuel`)).status()).toBe(200);
|
|
||||||
flyHome = await page.request.post(`/api/planes/${plane.id}/fly`, { data: { destIcao: HUB } });
|
|
||||||
}
|
|
||||||
expect(flyHome.ok()).toBeTruthy(); // repositioning needs no package (v0.12.0 manual flight)
|
expect(flyHome.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);
|
||||||
}
|
}
|
||||||
|
|||||||
+23
-73
@@ -5,15 +5,13 @@ import { expect, test } from '@playwright/test';
|
|||||||
import { initialBearingDeg } from '../lib/geo';
|
import { initialBearingDeg } from '../lib/geo';
|
||||||
import { weatherFor } from '../lib/weather';
|
import { weatherFor } from '../lib/weather';
|
||||||
import { windBurnFactor } from '../lib/sim/movement';
|
import { windBurnFactor } from '../lib/sim/movement';
|
||||||
// v0.38.0 (ISS-072) — reputation discounts: expectations computed from the LIVE snapshot's rep with the real helpers.
|
|
||||||
import { FUEL_DISCOUNT_PER_REP, MAX_FUEL_DISCOUNT, repRate } from '../lib/game/catalog';
|
|
||||||
|
|
||||||
// v0.31.0 — ISS-055: gameplay with TWO planes in the fleet. The reported bug ("can't load cargo
|
// v0.31.0 — ISS-055: gameplay with TWO planes in the fleet. The reported bug ("can't load cargo
|
||||||
// if both planes are on the same airport") was UX-only: LoadControls' multi-plane path rendered a
|
// if both planes are on the same airport") was UX-only: LoadControls' multi-plane path rendered a
|
||||||
// greyed-out Load button until a plane was picked from the dropdown, while the single-plane path
|
// greyed-out Load button until a plane was picked from the dropdown, while the single-plane path
|
||||||
// is one-click. v0.31.0 preselects the first eligible plane (components/RightPane.tsx), and this
|
// is one-click. v0.31.0 preselects the first eligible plane (components/RightPane.tsx), and this
|
||||||
// spec covers every two-plane flow: load (preselect + picker), parallel flights with the ISS-057
|
// spec covers every two-plane flow: load (preselect + picker), parallel flights with the ISS-057
|
||||||
// slow/resume semantics, refuel, relocate, per-plane queues (scoped testids) and sell.
|
// slow/resume semantics, relocate, per-plane queues (scoped testids) and sell.
|
||||||
//
|
//
|
||||||
// Each test buys its own second plane via the UI (after a cash grant from the new
|
// Each test buys its own second plane via the UI (after a cash grant from the new
|
||||||
// POST /api/test/add-cash hook — ATR €200k vs the €20k starting balance); beforeEach/afterEach
|
// POST /api/test/add-cash hook — ATR €200k vs the €20k starting balance); beforeEach/afterEach
|
||||||
@@ -171,6 +169,14 @@ async function addCash(page: Page, amount?: number): Promise<StateBody> {
|
|||||||
return (await res.json()) as StateBody;
|
return (await res.json()) as StateBody;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Test hook (FLIGHT_TEST_HOOKS=1): top a plane's tank back to full — replaces the removed /refuel
|
||||||
|
// endpoint (ISS-082). Reads maxFuel from the snapshot so no catalog mirror is needed.
|
||||||
|
async function setFuelFull(page: Page, planeId: string): Promise<void> {
|
||||||
|
const s = await getState(page);
|
||||||
|
const p = s.planes.find((x) => x.id === planeId)!;
|
||||||
|
expect((await page.request.post('/api/test/set-fuel', { data: { planeId, fuel: p.maxFuel } })).status()).toBe(200);
|
||||||
|
}
|
||||||
|
|
||||||
// Buy a second ATR through the UI (Planes market tab) and return its id — discovered in /api/state
|
// Buy a second ATR through the UI (Planes market tab) and return its id — discovered in /api/state
|
||||||
// as the plane that isn't plane-starter (bought planes get random UUIDs, no stable name).
|
// as the plane that isn't plane-starter (bought planes get random UUIDs, no stable name).
|
||||||
async function buySecondPlaneViaUi(page: Page): Promise<string> {
|
async function buySecondPlaneViaUi(page: Page): Promise<string> {
|
||||||
@@ -244,13 +250,10 @@ async function healPlaneHome(page: Page, planeId: string): Promise<void> {
|
|||||||
}
|
}
|
||||||
if (p.locationIcao !== HUB) {
|
if (p.locationIcao !== HUB) {
|
||||||
// ISS-057: the landing above slowed the sim to 1× — setScale restores 1000× for the return leg.
|
// ISS-057: the landing above slowed the sim to 1× — setScale restores 1000× for the return leg.
|
||||||
|
// ISS-082: dispatch auto-refuels, so a grounded plane can always start any full-tank-flyable
|
||||||
|
// leg when cash allows — no top-up retry needed.
|
||||||
await setScale(page, SCALE);
|
await setScale(page, SCALE);
|
||||||
let flyHome = await page.request.post(`/api/planes/${planeId}/fly`, { data: { destIcao: HUB } });
|
const flyHome = await page.request.post(`/api/planes/${planeId}/fly`, { data: { destIcao: HUB } });
|
||||||
if (flyHome.status() === 409) {
|
|
||||||
// A long outbound leg can leave the tank too empty for the return — top up and retry.
|
|
||||||
expect((await page.request.post(`/api/planes/${planeId}/refuel`)).status()).toBe(200);
|
|
||||||
flyHome = await page.request.post(`/api/planes/${planeId}/fly`, { data: { destIcao: HUB } });
|
|
||||||
}
|
|
||||||
expect(flyHome.status()).toBe(200);
|
expect(flyHome.status()).toBe(200);
|
||||||
await expect
|
await expect
|
||||||
.poll(async () => ((await getState(page)).planes.find((x) => x.id === planeId)?.locationIcao ?? ''), {
|
.poll(async () => ((await getState(page)).planes.find((x) => x.id === planeId)?.locationIcao ?? ''), {
|
||||||
@@ -275,8 +278,11 @@ async function sellNonStarters(page: Page): Promise<void> {
|
|||||||
// Canonical start state for every test: fleet of exactly one plane (the starter), grounded at EDDF,
|
// Canonical start state for every test: fleet of exactly one plane (the starter), grounded at EDDF,
|
||||||
// no cargo on board — even after an interrupted previous run.
|
// no cargo on board — even after an interrupted previous run.
|
||||||
async function resetFleet(page: Page): Promise<void> {
|
async function resetFleet(page: Page): Promise<void> {
|
||||||
|
// v0.39.0 (ISS-069): wear accumulates across the shared CI DB — restore full health and clear any
|
||||||
|
// active repair gate before healing, so the farthest-flyable picker never sees a worn/broken starter.
|
||||||
|
expect((await page.request.post('/api/test/set-health', { data: { planeId: STARTER, health: 100, repairUntilMs: 0 } })).status()).toBe(200);
|
||||||
await sellNonStarters(page);
|
await sellNonStarters(page);
|
||||||
await healPlaneHome(page, STARTER);
|
await healPlaneHome(page, STARTER); // the tick inside its getState flips a shortened gate back to available
|
||||||
await abandonLeftoverCargo(page, STARTER);
|
await abandonLeftoverCargo(page, STARTER);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -347,8 +353,8 @@ test('two planes fly in parallel; the last landing slows to 1× and the next dis
|
|||||||
const secondId = await buySecondPlaneViaUi(page);
|
const secondId = await buySecondPlaneViaUi(page);
|
||||||
|
|
||||||
// Full tanks for both — the starter's may be partial from an earlier run.
|
// Full tanks for both — the starter's may be partial from an earlier run.
|
||||||
expect((await page.request.post(`/api/planes/${STARTER}/refuel`)).status()).toBe(200);
|
await setFuelFull(page, STARTER);
|
||||||
expect((await page.request.post(`/api/planes/${secondId}/refuel`)).status()).toBe(200);
|
await setFuelFull(page, secondId);
|
||||||
|
|
||||||
// Two very different leg lengths: the starter takes the SHORTEST hop, the second plane the longest
|
// Two very different leg lengths: the starter takes the SHORTEST hop, the second plane the longest
|
||||||
// full-tank-flyable one — their landings are separated by hours of game time and can never fall on
|
// full-tank-flyable one — their landings are separated by hours of game time and can never fall on
|
||||||
@@ -399,8 +405,8 @@ test('two planes fly in parallel; the last landing slows to 1× and the next dis
|
|||||||
expect(landed.packages.find((p) => p.id === pkgA.id)?.status).toBe('delivered');
|
expect(landed.packages.find((p) => p.id === pkgA.id)?.status).toBe('delivered');
|
||||||
expect(landed.packages.find((p) => p.id === pkgB.id)?.status).toBe('delivered');
|
expect(landed.packages.find((p) => p.id === pkgB.id)?.status).toBe('delivered');
|
||||||
|
|
||||||
// The outbound to the range edge left the tank nearly empty — top up for the return leg.
|
// The outbound to the range edge left the tank nearly empty — top it back up (ISS-082 hook).
|
||||||
expect((await page.request.post(`/api/planes/${secondId}/refuel`)).status()).toBe(200);
|
await setFuelFull(page, secondId);
|
||||||
|
|
||||||
// Resume semantics: with the starter still grounded, dispatching the second plane does NOT resume…
|
// Resume semantics: with the starter still grounded, dispatching the second plane does NOT resume…
|
||||||
const flyB2 = await page.request.post(`/api/planes/${secondId}/fly`, { data: { destIcao: HUB } });
|
const flyB2 = await page.request.post(`/api/planes/${secondId}/fly`, { data: { destIcao: HUB } });
|
||||||
@@ -415,64 +421,8 @@ test('two planes fly in parallel; the last landing slows to 1× and the next dis
|
|||||||
expect(body.simState.timeScale, 'the last grounded plane resumes lastSelectedTimeScale').toBe(SCALE); // setScale posted 1000
|
expect(body.simState.timeScale, 'the last grounded plane resumes lastSelectedTimeScale').toBe(SCALE); // setScale posted 1000
|
||||||
});
|
});
|
||||||
|
|
||||||
test('refuel section lists both planes; refueling one tops only its tank', async ({ page }) => {
|
// ISS-082 (v0.42.0): the "refuel section lists both planes" test is gone with the manual refuel UI —
|
||||||
test.setTimeout(300_000); // self-heal + two short hops at scale 1000
|
// its absence is pinned in e2e/panes.spec.ts instead.
|
||||||
const secondId = await buySecondPlaneViaUi(page);
|
|
||||||
|
|
||||||
// Partial tanks: a short hop each, to different destinations.
|
|
||||||
const [a, b] = await twoNearestToHub(page);
|
|
||||||
expect((await page.request.post(`/api/planes/${STARTER}/refuel`)).status()).toBe(200);
|
|
||||||
expect((await page.request.post(`/api/planes/${secondId}/refuel`)).status()).toBe(200);
|
|
||||||
expect((await page.request.post(`/api/planes/${STARTER}/fly`, { data: { destIcao: a.icao } })).status()).toBe(200);
|
|
||||||
expect((await page.request.post(`/api/planes/${secondId}/fly`, { data: { destIcao: b.icao } })).status()).toBe(200);
|
|
||||||
|
|
||||||
// Fast-forward to the first landing, restore speed (ISS-057 slows on any landing), then wait for both.
|
|
||||||
await setScale(page, SCALE);
|
|
||||||
await expect
|
|
||||||
.poll(async () => ((await getState(page)).planes.some((p) => p.status === 'available')), {
|
|
||||||
timeout: 240_000,
|
|
||||||
message: 'waiting for the first plane to land',
|
|
||||||
})
|
|
||||||
.toBe(true);
|
|
||||||
await setScale(page, SCALE);
|
|
||||||
await expect
|
|
||||||
.poll(async () => ((await getState(page)).planes.every((p) => p.status === 'available')), {
|
|
||||||
timeout: 240_000,
|
|
||||||
message: 'waiting for both planes to land',
|
|
||||||
})
|
|
||||||
.toBe(true);
|
|
||||||
|
|
||||||
const pre = await getState(page);
|
|
||||||
const starter = pre.planes.find((p) => p.id === STARTER)!;
|
|
||||||
const second = pre.planes.find((p) => p.id === secondId)!;
|
|
||||||
expect(starter.fuel, 'the hop burned fuel').toBeLessThan(starter.maxFuel);
|
|
||||||
expect(second.fuel, 'the hop burned fuel').toBeLessThan(second.maxFuel);
|
|
||||||
|
|
||||||
// The left-pane Refuel section lists BOTH grounded planes with partial tanks…
|
|
||||||
const refuelSelect = page.getByTestId('market-refuel-plane');
|
|
||||||
await expect(refuelSelect).toBeVisible({ timeout: 15_000 });
|
|
||||||
await expect(refuelSelect.locator(`option[value="${STARTER}"]`)).toHaveCount(1);
|
|
||||||
await expect(refuelSelect.locator(`option[value="${secondId}"]`)).toHaveCount(1);
|
|
||||||
|
|
||||||
// …select the SECOND plane — the preview is its exact fill-up cost (mirrors refuelPlane 'full'),
|
|
||||||
// rep-scaled (v0.38.0, ISS-072) from the live snapshot's reputation.
|
|
||||||
const fuelRate = repRate(pre.account.reputation, FUEL_DISCOUNT_PER_REP, MAX_FUEL_DISCOUNT);
|
|
||||||
const expectedCost = Math.round((second.maxFuel - second.fuel) * pre.fuelPricePerL * (1 - fuelRate) * 100) / 100;
|
|
||||||
await refuelSelect.selectOption(secondId);
|
|
||||||
await expect(page.getByTestId('market-refuel-cost')).toContainText(eur(expectedCost));
|
|
||||||
|
|
||||||
await page.getByTestId('market-refuel').click();
|
|
||||||
await expect
|
|
||||||
.poll(async () => {
|
|
||||||
const s = await getState(page);
|
|
||||||
return Math.abs(s.account.cash - (pre.account.cash - expectedCost)) < 0.001;
|
|
||||||
}, { timeout: 15_000, message: 'waiting for the refuel cost to land in /api/state' })
|
|
||||||
.toBe(true);
|
|
||||||
|
|
||||||
const post = await getState(page);
|
|
||||||
expect(post.planes.find((p) => p.id === secondId)!.fuel, 'that tank is full').toBe(second.maxFuel);
|
|
||||||
expect(post.planes.find((p) => p.id === STARTER)!.fuel, 'the other tank is untouched').toBe(starter.fuel);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('relocate section moves one plane without touching the other', async ({ page }) => {
|
test('relocate section moves one plane without touching the other', async ({ page }) => {
|
||||||
test.setTimeout(300_000); // self-heal + one short hop at scale 1000
|
test.setTimeout(300_000); // self-heal + one short hop at scale 1000
|
||||||
@@ -524,7 +474,7 @@ test('per-plane queues are independent; landing auto-chains the next queued leg'
|
|||||||
const [a, b] = await twoNearestToHub(page);
|
const [a, b] = await twoNearestToHub(page);
|
||||||
|
|
||||||
// Full tank for the starter — it flies both legs (EDDF→a then the auto-chained a→b).
|
// Full tank for the starter — it flies both legs (EDDF→a then the auto-chained a→b).
|
||||||
expect((await page.request.post(`/api/planes/${STARTER}/refuel`)).status()).toBe(200);
|
await setFuelFull(page, STARTER);
|
||||||
|
|
||||||
// Seed one queued leg per plane via the API so BOTH on-board blocks render…
|
// Seed one queued leg per plane via the API so BOTH on-board blocks render…
|
||||||
expect((await page.request.post(`/api/planes/${STARTER}/queue`, { data: { destIcao: a.icao } })).status()).toBe(200);
|
expect((await page.request.post(`/api/planes/${STARTER}/queue`, { data: { destIcao: a.icao } })).status()).toBe(200);
|
||||||
|
|||||||
+11
-1
@@ -31,7 +31,9 @@ CREATE TABLE IF NOT EXISTS planes (
|
|||||||
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 '[]'
|
queue TEXT NOT NULL DEFAULT '[]',
|
||||||
|
health REAL NOT NULL DEFAULT 100,
|
||||||
|
repair_until_sim_time INTEGER
|
||||||
);
|
);
|
||||||
CREATE TABLE IF NOT EXISTS packages (
|
CREATE TABLE IF NOT EXISTS packages (
|
||||||
id TEXT PRIMARY KEY NOT NULL,
|
id TEXT PRIMARY KEY NOT NULL,
|
||||||
@@ -88,6 +90,14 @@ function migrateColumns(raw: RawSqlJsDatabase): void {
|
|||||||
if (!cols('packages').has('special')) {
|
if (!cols('packages').has('special')) {
|
||||||
raw.exec('ALTER TABLE packages ADD COLUMN special TEXT');
|
raw.exec('ALTER TABLE packages ADD COLUMN special TEXT');
|
||||||
}
|
}
|
||||||
|
// v0.39.0 (ISS-069): plane health — pre-existing rows backfill to full health.
|
||||||
|
if (!cols('planes').has('health')) {
|
||||||
|
raw.exec('ALTER TABLE planes ADD COLUMN health REAL NOT NULL DEFAULT 100');
|
||||||
|
}
|
||||||
|
// v0.39.0 (ISS-069): repair gate — nullable, no default; pre-existing rows stay NULL = not in repair.
|
||||||
|
if (!cols('planes').has('repair_until_sim_time')) {
|
||||||
|
raw.exec('ALTER TABLE planes ADD COLUMN repair_until_sim_time INTEGER');
|
||||||
|
}
|
||||||
// v0.30.0 (ISS-057): last-selected speed — pre-existing rows backfill to the row's OWN
|
// 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.
|
// 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')) {
|
if (!cols('sim_state').has('last_selected_time_scale')) {
|
||||||
|
|||||||
+9
-1
@@ -7,7 +7,9 @@ import { integer, real, sqliteTable, text } from 'drizzle-orm/sqlite-core';
|
|||||||
export const planes = sqliteTable('planes', {
|
export const planes = sqliteTable('planes', {
|
||||||
id: text('id').primaryKey().notNull(),
|
id: text('id').primaryKey().notNull(),
|
||||||
model: text('model').notNull(),
|
model: text('model').notNull(),
|
||||||
status: text('status', { enum: ['available', 'flying'] }).notNull(),
|
// v0.39.0 (ISS-069): 'repairing' = grounded in the shop until repairUntilSimTime passes; the
|
||||||
|
// engine flips it back to 'available' on a tick. All status guards key off 'available'.
|
||||||
|
status: text('status', { enum: ['available', 'flying', 'repairing'] }).notNull(),
|
||||||
fuel: real('fuel').notNull(),
|
fuel: real('fuel').notNull(),
|
||||||
maxFuel: real('max_fuel').notNull(),
|
maxFuel: real('max_fuel').notNull(),
|
||||||
locationIcao: text('location_icao').notNull(),
|
locationIcao: text('location_icao').notNull(),
|
||||||
@@ -24,6 +26,12 @@ export const planes = sqliteTable('planes', {
|
|||||||
// of ICAO strings ('[]' when empty). The ACTIVE leg stays destIcao +
|
// of ICAO strings ('[]' when empty). The ACTIVE leg stays destIcao +
|
||||||
// departureSimTime; on landing the engine auto-chains queue[0] if fuel covers it.
|
// departureSimTime; on landing the engine auto-chains queue[0] if fuel covers it.
|
||||||
queue: text('queue').notNull().default('[]'),
|
queue: text('queue').notNull().default('[]'),
|
||||||
|
// Structural health in [0, 100] (v0.39.0, ISS-069) — wears down by WEAR_PER_KM per km of
|
||||||
|
// landed legs; at 0 the plane is broken and burns BROKEN_BURN_MULTIPLIER × more fuel.
|
||||||
|
health: real('health').notNull().default(100),
|
||||||
|
// Sim-clock epoch ms when an active repair finishes (v0.39.0, ISS-069) — set with status
|
||||||
|
// 'repairing', cleared by the engine's flip-back pass; NULL = not in repair.
|
||||||
|
repairUntilSimTime: integer('repair_until_sim_time'),
|
||||||
});
|
});
|
||||||
|
|
||||||
// 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
|
||||||
|
|||||||
@@ -22,6 +22,8 @@ const basePlane = (id: string): PlaneState => ({
|
|||||||
departureSimTime: null,
|
departureSimTime: null,
|
||||||
lat: 50.03,
|
lat: 50.03,
|
||||||
lon: 8.56,
|
lon: 8.56,
|
||||||
|
health: 100, // v0.39.0 (ISS-069) — full-health fixture default
|
||||||
|
repairUntilSimTime: null,
|
||||||
queue: [],
|
queue: [],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
+158
-168
@@ -10,12 +10,15 @@ import { haversineKm, initialBearingDeg } from '@/lib/geo';
|
|||||||
import { weatherFor } from '@/lib/weather';
|
import { weatherFor } from '@/lib/weather';
|
||||||
import { requiredFuelFor, windBurnFactor } from '@/lib/sim/movement';
|
import { requiredFuelFor, windBurnFactor } from '@/lib/sim/movement';
|
||||||
import {
|
import {
|
||||||
|
BROKEN_BURN_MULTIPLIER,
|
||||||
FUEL_DISCOUNT_PER_REP,
|
FUEL_DISCOUNT_PER_REP,
|
||||||
FUEL_PRICE_PER_L,
|
FUEL_PRICE_PER_L,
|
||||||
MAX_FUEL_DISCOUNT,
|
MAX_FUEL_DISCOUNT,
|
||||||
MAX_PLANE_DISCOUNT,
|
MAX_PLANE_DISCOUNT,
|
||||||
PLANE_DISCOUNT_PER_REP,
|
PLANE_DISCOUNT_PER_REP,
|
||||||
PLANE_TYPES,
|
PLANE_TYPES,
|
||||||
|
REPAIR_COST,
|
||||||
|
REPAIR_DURATION_MS,
|
||||||
repRate,
|
repRate,
|
||||||
SELL_FRACTION,
|
SELL_FRACTION,
|
||||||
} from './catalog';
|
} from './catalog';
|
||||||
@@ -29,7 +32,7 @@ import {
|
|||||||
ignorePackage,
|
ignorePackage,
|
||||||
loadPackage,
|
loadPackage,
|
||||||
queueLeg,
|
queueLeg,
|
||||||
refuelPlane,
|
repairPlane,
|
||||||
sellPlane,
|
sellPlane,
|
||||||
} from './actions';
|
} from './actions';
|
||||||
|
|
||||||
@@ -227,11 +230,115 @@ describe('flyPlane', () => {
|
|||||||
await expectActionError(flyPlane(inst, 'plane-starter', 'ZZZZ'), 400, /unknown airport/);
|
await expectActionError(flyPlane(inst, 'plane-starter', 'ZZZZ'), 400, /unknown airport/);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('rejects a leg the plane cannot fuel with 409 (burn > fuel)', async () => {
|
it('uses the ×1.5 broken burn for the dispatch auto-top-up when health is 0 (v0.39.0, ISS-069)', async () => {
|
||||||
const inst = await freshDb('fly-nofuel.db'); // EDDF → LEMD ≈ 1950 km × 1.75 L/km ≈ 3400 L
|
const inst = await freshDb('fly-broken.db'); // EDDF → LEMD
|
||||||
await inst.db.update(schema.planes).set({ fuel: 1 }).where(eq(schema.planes.id, '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 w = weatherFor(HUB_ICAO);
|
||||||
|
const f = windBurnFactor(w.windKt, w.windDirDeg, initialBearingDeg(from.lat, from.lon, to.lat, to.lon));
|
||||||
|
// The tank holds EXACTLY the healthy requirement — a broken plane's 150% top-up target is higher.
|
||||||
|
const healthyRequired = requiredFuelFor(type.burnPerKm * f, type.emptyWeightKg, type.maxFuel, km);
|
||||||
|
await inst.db.update(schema.planes)
|
||||||
|
.set({ health: 0, fuel: healthyRequired })
|
||||||
|
.where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
await expectActionError(flyPlane(inst, 'plane-starter', 'LEMD'), 409, /insufficient fuel/i);
|
await flyPlane(inst, 'plane-starter', 'LEMD'); // auto-refuel covers the extra burn — no 409
|
||||||
|
|
||||||
|
const brokenRequired = requiredFuelFor(type.burnPerKm * f * BROKEN_BURN_MULTIPLIER, type.emptyWeightKg, type.maxFuel, km);
|
||||||
|
expect(brokenRequired).toBeGreaterThan(healthyRequired); // sanity: the multiplier genuinely raises the requirement
|
||||||
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
|
expect(plane.status).toBe('flying');
|
||||||
|
expect(plane.fuel).toBeCloseTo(Math.min(type.maxFuel, Math.max(healthyRequired, brokenRequired * 1.5)), 6); // topped up for the BROKEN burn…
|
||||||
|
|
||||||
|
// …while the same tank at full health tops up to the LOWER healthy target — the multiplier is what raised it.
|
||||||
|
const inst2 = await freshDb('fly-broken-healthy.db');
|
||||||
|
await inst2.db.update(schema.planes).set({ fuel: healthyRequired }).where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
await flyPlane(inst2, 'plane-starter', 'LEMD'); // must not throw
|
||||||
|
const plane2 = (await inst2.db.select().from(schema.planes))[0];
|
||||||
|
expect(plane2.fuel).toBeCloseTo(Math.min(type.maxFuel, Math.max(healthyRequired, healthyRequired * 1.5)), 6);
|
||||||
|
expect(plane.fuel).toBeGreaterThan(plane2.fuel); // the broken plane genuinely got more fuel
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- Auto-refuel on dispatch (ISS-082, v0.42.0) ---
|
||||||
|
|
||||||
|
// Wind-adjusted requirement for the hub → LEMD leg — computed with the SAME helpers flyPlane uses,
|
||||||
|
// so the expectations stay exact without hardcoded literals.
|
||||||
|
async function adjustedRequiredForHubToLemd() {
|
||||||
|
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 w = weatherFor(HUB_ICAO);
|
||||||
|
return requiredFuelFor(
|
||||||
|
type.burnPerKm * windBurnFactor(w.windKt, w.windDirDeg, initialBearingDeg(from.lat, from.lon, to.lat, to.lon)),
|
||||||
|
type.emptyWeightKg,
|
||||||
|
type.maxFuel,
|
||||||
|
km,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
it('auto-refuels on dispatch: tops up to min(maxFuel, max(fuel, 1.5 × required)) and deducts the rep-discounted cost', async () => {
|
||||||
|
const inst = await freshDb('fly-autorefuel.db'); // EDDF → LEMD
|
||||||
|
const required = await adjustedRequiredForHubToLemd();
|
||||||
|
const startFuel = Math.round(required / 2); // partial tank below the requirement
|
||||||
|
await inst.db.update(schema.planes).set({ fuel: startFuel }).where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
// Elevated rep → non-zero discount rate; expectations computed with the SAME helpers flyPlane uses.
|
||||||
|
await inst.db.update(schema.account).set({ reputation: 30 });
|
||||||
|
const cashBefore = (await inst.db.select().from(schema.account))[0].cash;
|
||||||
|
|
||||||
|
await flyPlane(inst, 'plane-starter', 'LEMD');
|
||||||
|
|
||||||
|
const rate = repRate(30, FUEL_DISCOUNT_PER_REP, MAX_FUEL_DISCOUNT);
|
||||||
|
expect(rate).toBeGreaterThan(0); // sanity pin on the formula input
|
||||||
|
const target = Math.min(PLANE_TYPES.atr72.maxFuel, Math.max(startFuel, required * 1.5));
|
||||||
|
const expectedCost = Math.round((target - startFuel) * FUEL_PRICE_PER_L * (1 - rate) * 100) / 100;
|
||||||
|
expect(expectedCost).toBeGreaterThan(0); // the top-up genuinely costs something
|
||||||
|
|
||||||
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
|
expect(plane.status).toBe('flying');
|
||||||
|
expect(plane.fuel).toBeCloseTo(target, 6); // topped up to exactly the 150% target…
|
||||||
|
const account = (await inst.db.select().from(schema.account))[0];
|
||||||
|
expect(account.cash).toBeCloseTo(cashBefore - expectedCost, 6); // …at exactly the rep-discounted cost
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is a free no-op when the tank already covers the 150% target (cash unchanged)', async () => {
|
||||||
|
const inst = await freshDb('fly-autorefuel-full.db'); // seeded starter is full at EDDF
|
||||||
|
const required = await adjustedRequiredForHubToLemd();
|
||||||
|
expect(required * 1.5).toBeLessThan(PLANE_TYPES.atr72.maxFuel); // sanity: the target stays below a full tank
|
||||||
|
const cashBefore = (await inst.db.select().from(schema.account))[0].cash;
|
||||||
|
|
||||||
|
await flyPlane(inst, 'plane-starter', 'LEMD');
|
||||||
|
|
||||||
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
|
expect(plane.status).toBe('flying');
|
||||||
|
expect(plane.fuel).toBe(PLANE_TYPES.atr72.maxFuel); // untouched…
|
||||||
|
expect((await inst.db.select().from(schema.account))[0].cash).toBe(cashBefore); // …and free
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects dispatch with 409 insufficient funds when cash cannot cover the top-up — nothing mutated', async () => {
|
||||||
|
const inst = await freshDb('fly-autorefuel-poor.db'); // EDDF → LEMD
|
||||||
|
const required = await adjustedRequiredForHubToLemd();
|
||||||
|
const startFuel = Math.round(required / 2);
|
||||||
|
await inst.db.update(schema.planes).set({ fuel: startFuel }).where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
await inst.db.update(schema.account).set({ cash: 0 });
|
||||||
|
|
||||||
|
await expectActionError(flyPlane(inst, 'plane-starter', 'LEMD'), 409, /insufficient funds/i);
|
||||||
|
|
||||||
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
|
expect(plane.status).toBe('available'); // still grounded…
|
||||||
|
expect(plane.fuel).toBe(startFuel); // …with the fuel UNCHANGED — nothing was mutated
|
||||||
|
});
|
||||||
|
|
||||||
|
it('still rejects a leg that does not fit even a full tank with 409 (the auto-refuel backstop)', async () => {
|
||||||
|
const inst = await freshDb('fly-autorefuel-nofit.db');
|
||||||
|
// UNNT ↔ LPPD are ~7670 km apart — far beyond the ATR's range, so no top-up can make it flyable.
|
||||||
|
await inst.db.update(schema.planes).set({ locationIcao: 'UNNT' }).where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
|
await expectActionError(flyPlane(inst, 'plane-starter', 'LPPD'), 409, /insufficient fuel/i);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -584,198 +691,81 @@ describe('sellPlane', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('refuelPlane', () => {
|
describe('repairPlane (v0.39.0, ISS-069)', () => {
|
||||||
it('fills to maxFuel and deducts (maxFuel − fuel) × FUEL_PRICE_PER_L from cash', async () => {
|
it('charges exactly REPAIR_COST, restores health to 100 and grounds the plane for REPAIR_DURATION_MS', async () => {
|
||||||
const inst = await freshDb('refuel-ok.db');
|
const inst = await freshDb('repair-ok.db');
|
||||||
await inst.db.update(schema.planes).set({ fuel: 1_000 }).where(eq(schema.planes.id, 'plane-starter'));
|
await inst.db.update(schema.planes).set({ health: 42 }).where(eq(schema.planes.id, 'plane-starter'));
|
||||||
const cashBefore = (await inst.db.select().from(schema.account))[0].cash;
|
const cashBefore = (await inst.db.select().from(schema.account))[0].cash;
|
||||||
|
|
||||||
const { cost } = await refuelPlane(inst, 'plane-starter');
|
const { cost } = await repairPlane(inst, 'plane-starter');
|
||||||
|
|
||||||
expect(cost).toBe(Math.round((PLANE_TYPES.atr72.maxFuel - 1_000) * FUEL_PRICE_PER_L * 100) / 100);
|
expect(cost).toBe(REPAIR_COST);
|
||||||
const plane = (await inst.db.select().from(schema.planes))[0];
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
expect(plane.fuel).toBe(PLANE_TYPES.atr72.maxFuel);
|
expect(plane.status).toBe('repairing');
|
||||||
|
expect(plane.health).toBe(100); // restored to full…
|
||||||
|
expect(plane.repairUntilSimTime).toBe(T0 + REPAIR_DURATION_MS); // …with the gate set from the seeded clock (no tick in direct calls)
|
||||||
const account = (await inst.db.select().from(schema.account))[0];
|
const account = (await inst.db.select().from(schema.account))[0];
|
||||||
expect(account.cash).toBeCloseTo(cashBefore - cost, 6);
|
expect(account.cash).toBeCloseTo(cashBefore - REPAIR_COST, 6);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('is a free no-op when the tank is already full', async () => {
|
it('is a free no-op when health is already full', async () => {
|
||||||
const inst = await freshDb('refuel-full.db'); // seeded starter is full
|
const inst = await freshDb('repair-full.db'); // seeded starter at 100
|
||||||
const cashBefore = (await inst.db.select().from(schema.account))[0].cash;
|
const cashBefore = (await inst.db.select().from(schema.account))[0].cash;
|
||||||
|
|
||||||
const { cost } = await refuelPlane(inst, 'plane-starter');
|
const { cost } = await repairPlane(inst, 'plane-starter');
|
||||||
|
|
||||||
expect(cost).toBe(0);
|
expect(cost).toBe(0);
|
||||||
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
|
expect(plane.status).toBe('available'); // not grounded…
|
||||||
|
expect(plane.health).toBe(100);
|
||||||
|
expect(plane.repairUntilSimTime ?? null).toBeNull(); // …and no gate set
|
||||||
expect((await inst.db.select().from(schema.account))[0].cash).toBe(cashBefore);
|
expect((await inst.db.select().from(schema.account))[0].cash).toBe(cashBefore);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('rejects a flying plane with 409', async () => {
|
it('rejects a flying plane with 409', async () => {
|
||||||
const inst = await freshDb('refuel-flying.db');
|
const inst = await freshDb('repair-flying.db');
|
||||||
await inst.db.update(schema.planes)
|
await inst.db.update(schema.planes)
|
||||||
.set({ status: 'flying', departureSimTime: T0, destIcao: 'LEMD' })
|
.set({ status: 'flying', departureSimTime: T0, destIcao: 'LEMD' })
|
||||||
.where(eq(schema.planes.id, 'plane-starter'));
|
.where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
await expectActionError(refuelPlane(inst, 'plane-starter'), 409, /flying/);
|
await expectActionError(repairPlane(inst, 'plane-starter'), 409, /only grounded planes can be repaired/);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('rejects the fill-up when cash is below the cost with 409', async () => {
|
it('rejects a plane that is already repairing with 409', async () => {
|
||||||
const inst = await freshDb('refuel-poor.db');
|
const inst = await freshDb('repair-busy.db');
|
||||||
await inst.db.update(schema.planes).set({ fuel: 1_000 }).where(eq(schema.planes.id, 'plane-starter'));
|
await inst.db.update(schema.planes)
|
||||||
await inst.db.update(schema.account).set({ cash: 10 }); // cost is ~4960
|
.set({ status: 'repairing', repairUntilSimTime: T0 + REPAIR_DURATION_MS })
|
||||||
|
.where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
await expectActionError(refuelPlane(inst, 'plane-starter'), 409, /insufficient funds/i);
|
await expectActionError(repairPlane(inst, 'plane-starter'), 409, /only grounded planes can be repaired/);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('applies the reputation-scaled discount to the price term only, in both modes (v0.38.0)', async () => {
|
it('blocks load/fly/sell while repairing (the existing status guards)', async () => {
|
||||||
const inst = await freshDb('refuel-rep.db');
|
const inst = await freshDb('repair-blocks.db');
|
||||||
// Elevated rep → non-zero rate; expectations computed with the SAME helpers refuelPlane uses.
|
await inst.db.update(schema.planes).set({ health: 50 }).where(eq(schema.planes.id, 'plane-starter'));
|
||||||
await inst.db.update(schema.account).set({ reputation: 30 });
|
await repairPlane(inst, 'plane-starter');
|
||||||
const rate = repRate(30, FUEL_DISCOUNT_PER_REP, MAX_FUEL_DISCOUNT);
|
|
||||||
expect(rate).toBeGreaterThan(0);
|
|
||||||
|
|
||||||
// 'full': exact discounted cost, tank math untouched.
|
await insertOpenPackage(inst); // open package at the hub — loadable if the plane were grounded
|
||||||
await inst.db.update(schema.planes).set({ fuel: 1_000 }).where(eq(schema.planes.id, 'plane-starter'));
|
await expectActionError(loadPackage(inst, 'p-open', 'plane-starter'), 409, /repairing/);
|
||||||
const cashBefore = (await inst.db.select().from(schema.account))[0].cash;
|
await expectActionError(flyPlane(inst, 'plane-starter', 'LEMD'), 409, /repairing/);
|
||||||
const { cost } = await refuelPlane(inst, 'plane-starter');
|
// A second plane so the "last remaining" guard cannot fire before the status one.
|
||||||
expect(cost).toBe(Math.round((PLANE_TYPES.atr72.maxFuel - 1_000) * FUEL_PRICE_PER_L * (1 - rate) * 100) / 100);
|
await inst.db.insert(schema.planes).values({
|
||||||
const plane = (await inst.db.select().from(schema.planes))[0];
|
id: 'plane-extra', model: 'atr72', status: 'available', fuel: 100, maxFuel: PLANE_TYPES.atr72.maxFuel,
|
||||||
expect(plane.fuel).toBe(PLANE_TYPES.atr72.maxFuel); // target unchanged by the discount
|
locationIcao: HUB_ICAO, destIcao: null, lat: 50, lon: 8, departureSimTime: null,
|
||||||
expect((await inst.db.select().from(schema.account))[0].cash).toBeCloseTo(cashBefore - cost, 6);
|
});
|
||||||
|
await expectActionError(sellPlane(inst, 'plane-starter'), 409, /repairing/);
|
||||||
|
});
|
||||||
|
|
||||||
// 'forFlight': same discount on the price term; burn/target math (wind factor, ×1.5 margin) untouched.
|
it('rejects the repair when cash is below REPAIR_COST with 409', async () => {
|
||||||
await insertOpenPackage(inst, 'p-ff-r', { destIcao: 'LEMD' }); // EDDF → LEMD
|
const inst = await freshDb('repair-poor.db');
|
||||||
await loadPackage(inst, 'p-ff-r', 'plane-starter');
|
await inst.db.update(schema.planes).set({ health: 50 }).where(eq(schema.planes.id, 'plane-starter'));
|
||||||
const required = await adjustedRequiredForHubToLemd();
|
await inst.db.update(schema.account).set({ cash: REPAIR_COST - 1 });
|
||||||
const startFuel = Math.round(required / 2);
|
|
||||||
await inst.db.update(schema.planes).set({ fuel: startFuel }).where(eq(schema.planes.id, 'plane-starter'));
|
|
||||||
const cashBefore2 = (await inst.db.select().from(schema.account))[0].cash;
|
|
||||||
|
|
||||||
const { cost: ffCost } = await refuelPlane(inst, 'plane-starter', { mode: 'forFlight', packageId: 'p-ff-r' });
|
await expectActionError(repairPlane(inst, 'plane-starter'), 409, /insufficient funds/i);
|
||||||
|
|
||||||
const targetFuel = Math.min(PLANE_TYPES.atr72.maxFuel, Math.max(startFuel, required * 1.5));
|
|
||||||
expect(ffCost).toBe(Math.round((targetFuel - startFuel) * FUEL_PRICE_PER_L * (1 - rate) * 100) / 100);
|
|
||||||
const plane2 = (await inst.db.select().from(schema.planes))[0];
|
|
||||||
expect(plane2.fuel).toBeCloseTo(targetFuel, 6); // topped up to exactly the 150% target
|
|
||||||
expect((await inst.db.select().from(schema.account))[0].cash).toBeCloseTo(cashBefore2 - ffCost, 6);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('rejects an unknown id with 404', async () => {
|
it('rejects an unknown id with 404', async () => {
|
||||||
const inst = await freshDb('refuel-unknown.db');
|
const inst = await freshDb('repair-unknown.db');
|
||||||
await expectActionError(refuelPlane(inst, 'ghost'), 404);
|
await expectActionError(repairPlane(inst, 'ghost'), 404);
|
||||||
});
|
|
||||||
|
|
||||||
// --- forFlight mode (v0.16.0) ---
|
|
||||||
|
|
||||||
// Wind-adjusted requirement for the hub → LEMD leg (v0.36.0) — computed with the SAME helpers
|
|
||||||
// refuelPlane uses, so the expectations stay exact without hardcoded literals.
|
|
||||||
async function adjustedRequiredForHubToLemd() {
|
|
||||||
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 w = weatherFor(HUB_ICAO);
|
|
||||||
return requiredFuelFor(
|
|
||||||
type.burnPerKm * windBurnFactor(w.windKt, w.windDirDeg, initialBearingDeg(from.lat, from.lon, to.lat, to.lon)),
|
|
||||||
type.emptyWeightKg,
|
|
||||||
type.maxFuel,
|
|
||||||
km,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
it('forFlight buys 150% of the weather-adjusted leg requirement 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 required = await adjustedRequiredForHubToLemd();
|
|
||||||
|
|
||||||
// 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' });
|
|
||||||
|
|
||||||
// ISS-071: target is 150% of the requirement (below tank capacity for this leg).
|
|
||||||
const targetFuel = Math.min(PLANE_TYPES.atr72.maxFuel, Math.max(startFuel, required * 1.5));
|
|
||||||
expect(cost).toBe(Math.round((targetFuel - startFuel) * FUEL_PRICE_PER_L * 100) / 100);
|
|
||||||
const plane = (await inst.db.select().from(schema.planes))[0];
|
|
||||||
expect(plane.fuel).toBeCloseTo(targetFuel, 6); // topped up to exactly the 150% target
|
|
||||||
const account = (await inst.db.select().from(schema.account))[0];
|
|
||||||
expect(account.cash).toBeCloseTo(cashBefore - cost, 6);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('forFlight leaves a tank with a 50% margin — 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 required = await adjustedRequiredForHubToLemd();
|
|
||||||
|
|
||||||
// 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 — the 150% margin covers flyPlane's strict `>` check.
|
|
||||||
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,
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+52
-71
@@ -9,12 +9,15 @@ import { requiredFuelFor, windBurnFactor } from '@/lib/sim/movement';
|
|||||||
import { runAction } from '@/lib/sim/engine';
|
import { runAction } from '@/lib/sim/engine';
|
||||||
import { getStateSnapshot, parseIcaoQueue } from './state';
|
import { getStateSnapshot, parseIcaoQueue } from './state';
|
||||||
import {
|
import {
|
||||||
|
conditionBurnMultiplier,
|
||||||
FUEL_DISCOUNT_PER_REP,
|
FUEL_DISCOUNT_PER_REP,
|
||||||
FUEL_PRICE_PER_L,
|
FUEL_PRICE_PER_L,
|
||||||
MAX_FUEL_DISCOUNT,
|
MAX_FUEL_DISCOUNT,
|
||||||
MAX_PLANE_DISCOUNT,
|
MAX_PLANE_DISCOUNT,
|
||||||
PLANE_DISCOUNT_PER_REP,
|
PLANE_DISCOUNT_PER_REP,
|
||||||
PLANE_TYPES,
|
PLANE_TYPES,
|
||||||
|
REPAIR_COST,
|
||||||
|
REPAIR_DURATION_MS,
|
||||||
repRate,
|
repRate,
|
||||||
SELL_FRACTION,
|
SELL_FRACTION,
|
||||||
} from './catalog';
|
} from './catalog';
|
||||||
@@ -22,9 +25,9 @@ import { abandonPenalty } from './penalty';
|
|||||||
import { HUB_ICAO } from './seed';
|
import { HUB_ICAO } from './seed';
|
||||||
|
|
||||||
// Player actions (v0.8.0, package model v0.12.0) — the core loop, server-side:
|
// Player actions (v0.8.0, package model v0.12.0) — the core loop, server-side:
|
||||||
// load a package onto a grounded plane at its origin, fly to any airport, deliver
|
// load a package onto a grounded plane at its origin, fly to any airport (dispatch
|
||||||
// on arrival, abandon for a penalty while grounded; plus buy/sell planes and
|
// auto-refuels first — ISS-082), deliver on arrival, abandon for a penalty while
|
||||||
// refuel. Each function validates and mutates ONE throwaway-safe GameDb instance
|
// grounded; plus buy/sell planes. Each function validates and mutates ONE throwaway-safe GameDb instance
|
||||||
// (persisted at the end); routes wrap them in engine.runAction() so tick +
|
// (persisted at the end); routes wrap them in engine.runAction() so tick +
|
||||||
// validate + mutate are atomic under the sim lock. Validation failures throw
|
// validate + mutate are atomic under the sim lock. Validation failures throw
|
||||||
// GameActionError carrying the HTTP status:
|
// GameActionError carrying the HTTP status:
|
||||||
@@ -99,7 +102,11 @@ export async function loadPackage(inst: GameDb, packageId: string, planeId: stri
|
|||||||
// Manual flight (v0.12.0): a grounded plane can fly to ANY known airport — its
|
// Manual flight (v0.12.0): a grounded plane can fly to ANY known airport — its
|
||||||
// loaded packages' destinations or pure repositioning. On arrival the engine
|
// loaded packages' destinations or pure repositioning. On arrival the engine
|
||||||
// delivers whatever is bound for that airport. Validation: plane 'available',
|
// delivers whatever is bound for that airport. Validation: plane 'available',
|
||||||
// destination in the airport dataset, enough fuel for the leg.
|
// destination in the airport dataset, enough fuel for the leg. ISS-082 (v0.42.0):
|
||||||
|
// dispatch AUTO-refuels first — the tank is topped up to min(maxFuel, max(fuel, 1.5 × required))
|
||||||
|
// at FUEL_PRICE_PER_L per liter minus the rep-scaled discount, deducted from cash; a leg that
|
||||||
|
// doesn't fit even a full tank still 409s (insufficient fuel), and an unaffordable top-up 409s
|
||||||
|
// with nothing mutated.
|
||||||
export async function flyPlane(inst: GameDb, planeId: string, destIcao: string): Promise<void> {
|
export async function flyPlane(inst: GameDb, planeId: string, destIcao: string): Promise<void> {
|
||||||
const planeRows = await inst.db.select().from(schema.planes).where(eq(schema.planes.id, planeId));
|
const planeRows = await inst.db.select().from(schema.planes).where(eq(schema.planes.id, planeId));
|
||||||
const plane = planeRows[0];
|
const plane = planeRows[0];
|
||||||
@@ -118,11 +125,26 @@ export async function flyPlane(inst: GameDb, planeId: string, destIcao: string):
|
|||||||
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);
|
||||||
// Weighted burn model (v0.16.0): the leg needs enough fuel to cover it arriving empty; wind-
|
// Weighted burn model (v0.16.0): the leg needs enough fuel to cover it arriving empty; wind-
|
||||||
// adjusted (v0.36.0) by departure weather vs route heading — every call site uses this same factor.
|
// adjusted (v0.36.0) by departure weather vs route heading — every call site uses this same factor.
|
||||||
|
// v0.39.0 (ISS-069): a broken plane (health ≤ 0) burns BROKEN_BURN_MULTIPLIER × more per km.
|
||||||
const w = weatherFor(plane.locationIcao);
|
const w = weatherFor(plane.locationIcao);
|
||||||
const burnPerKm = type.burnPerKm * windBurnFactor(w.windKt, w.windDirDeg, initialBearingDeg(origin.lat, origin.lon, destFeature.properties.lat, destFeature.properties.lon));
|
const burnPerKm = type.burnPerKm * windBurnFactor(w.windKt, w.windDirDeg, initialBearingDeg(origin.lat, origin.lon, destFeature.properties.lat, destFeature.properties.lon)) * conditionBurnMultiplier(plane.health);
|
||||||
const requiredL = requiredFuelFor(burnPerKm, type.emptyWeightKg, type.maxFuel, distanceKm);
|
const requiredL = requiredFuelFor(burnPerKm, type.emptyWeightKg, type.maxFuel, distanceKm);
|
||||||
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`);
|
// ISS-082 (v0.42.0): dispatch auto-refuels — top up to 150% of the requirement (capped at tank
|
||||||
|
// capacity) so burn variance doesn't strand the plane; cost = liters × FUEL_PRICE_PER_L minus
|
||||||
|
// the rep-scaled discount (same price term as the removed manual refuel). All checks run BEFORE
|
||||||
|
// any mutation, so a 409 leaves fuel and cash untouched.
|
||||||
|
const target = Math.min(plane.maxFuel, Math.max(plane.fuel, requiredL * 1.5));
|
||||||
|
const liters = Math.max(0, target - plane.fuel);
|
||||||
|
const account = (await inst.db.select().from(schema.account))[0];
|
||||||
|
if (!account) throw new Error('account row missing');
|
||||||
|
const cost = Math.round(liters * FUEL_PRICE_PER_L * (1 - repRate(account.reputation, FUEL_DISCOUNT_PER_REP, MAX_FUEL_DISCOUNT)) * 100) / 100;
|
||||||
|
if (cost > 0 && account.cash < cost) {
|
||||||
|
throw new GameActionError(409, `insufficient funds: refueling costs ${cost}, you have ${Math.round(account.cash)}`);
|
||||||
|
}
|
||||||
|
// Backstop: a leg that doesn't fit even a full tank is unflyable (target caps at maxFuel).
|
||||||
|
if (requiredL > target) {
|
||||||
|
throw new GameActionError(409, `insufficient fuel: the leg needs ${Math.round(requiredL)} L but the plane has ${Math.round(target)} L`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// runAction() ticked first, so this is current game time.
|
// runAction() ticked first, so this is current game time.
|
||||||
@@ -136,8 +158,12 @@ export async function flyPlane(inst: GameDb, planeId: string, destIcao: string):
|
|||||||
departureSimTime: sim.clockMs,
|
departureSimTime: sim.clockMs,
|
||||||
lat: origin.lat,
|
lat: origin.lat,
|
||||||
lon: origin.lon,
|
lon: origin.lon,
|
||||||
|
fuel: target, // ISS-082: the post-top-up level (unchanged when no top-up was needed)
|
||||||
})
|
})
|
||||||
.where(eq(schema.planes.id, planeId));
|
.where(eq(schema.planes.id, planeId));
|
||||||
|
if (cost > 0) {
|
||||||
|
await inst.db.update(schema.account).set({ cash: Math.round((account.cash - cost) * 100) / 100 });
|
||||||
|
}
|
||||||
// ISS-057: dispatch still resumes a MANUALLY paused sim (pause is manual-only now — landings
|
// 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
|
// 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 took the LAST grounded plane airborne. Runs inside runAction(), so tick + controls
|
||||||
@@ -284,6 +310,7 @@ export async function buyPlane(inst: GameDb, model: string): Promise<{ planeId:
|
|||||||
lat: home.lat,
|
lat: home.lat,
|
||||||
lon: home.lon,
|
lon: home.lon,
|
||||||
departureSimTime: null,
|
departureSimTime: null,
|
||||||
|
health: 100, // new planes arrive at full health (v0.39.0, ISS-069)
|
||||||
});
|
});
|
||||||
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 });
|
||||||
await persist(inst);
|
await persist(inst);
|
||||||
@@ -326,82 +353,36 @@ export async function sellPlane(inst: GameDb, planeId: string): Promise<{ payout
|
|||||||
return { payout };
|
return { payout };
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Refuel (POST /api/planes/:planeId/refuel) ---
|
// --- Repair (POST /api/planes/:planeId/repair) — v0.39.0 (ISS-069) ---
|
||||||
|
|
||||||
// Refuel modes (v0.16.0): 'full' fills the tank to maxFuel; 'forFlight' buys 150% of
|
// Restore a worn-out plane to full health for the flat REPAIR_COST; it is grounded in 'repairing'
|
||||||
// the fuel required for one loaded package's destination leg (ISS-071) — wind-adjusted
|
// status until sim.clockMs + REPAIR_DURATION_MS, when the engine's tick flips it back to
|
||||||
// requirement per the weighted burn model, capped at tank capacity, independent of how
|
// 'available'. Only GROUNDED planes can be repaired (409 otherwise); an already-full-health
|
||||||
// much is already in the tank.
|
// repair is a free no-op. 404 unknown plane; 409 not grounded / insufficient funds.
|
||||||
export interface RefuelOptions {
|
export async function repairPlane(inst: GameDb, planeId: string): Promise<{ cost: number }> {
|
||||||
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`);
|
||||||
if (plane.status !== 'available') {
|
if (plane.status !== 'available') {
|
||||||
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 repaired`);
|
||||||
}
|
}
|
||||||
|
// Free no-op when the plane is already at full health — nothing to repair.
|
||||||
|
if (plane.health >= 100) return { cost: 0 };
|
||||||
|
|
||||||
const mode = opts.mode ?? 'full';
|
const sim = (await inst.db.select().from(schema.simState))[0];
|
||||||
let targetFuel: number; // tank level after the refuel
|
if (!sim) throw new Error('sim_state row missing');
|
||||||
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);
|
|
||||||
// Same wind-adjusted requirement flyPlane checks (v0.36.0) — departure weather vs route heading.
|
|
||||||
const w = weatherFor(plane.locationIcao);
|
|
||||||
const requiredL = requiredFuelFor(
|
|
||||||
type.burnPerKm * windBurnFactor(w.windKt, w.windDirDeg, initialBearingDeg(origin.lat, origin.lon, dest.lat, dest.lon)),
|
|
||||||
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`);
|
|
||||||
}
|
|
||||||
// ISS-071: buy 150% of the requirement (capped at tank capacity) so burn variance doesn't strand
|
|
||||||
// the plane. The margin makes flyPlane's strict `>` check pass with room to spare; already enough
|
|
||||||
// → free no-op, tank untouched.
|
|
||||||
targetFuel = Math.min(plane.maxFuel, Math.max(plane.fuel, requiredL * 1.5));
|
|
||||||
} 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 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');
|
||||||
// v0.38.0 (ISS-072): rep-scaled discount on the PRICE term only — the burn/target math above is untouched.
|
if (account.cash < REPAIR_COST) {
|
||||||
const cost = Math.round(liters * FUEL_PRICE_PER_L * (1 - repRate(account.reputation, FUEL_DISCOUNT_PER_REP, MAX_FUEL_DISCOUNT)) * 100) / 100;
|
throw new GameActionError(409, `insufficient funds: repair costs ${REPAIR_COST}, you have ${Math.round(account.cash)}`);
|
||||||
if (cost > 0 && account.cash < cost) {
|
|
||||||
throw new GameActionError(409, `insufficient funds: refueling costs ${cost}, you have ${Math.round(account.cash)}`);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await inst.db.update(schema.planes).set({ fuel: targetFuel }).where(eq(schema.planes.id, planeId));
|
await inst.db.update(schema.planes)
|
||||||
if (cost > 0) {
|
.set({ health: 100, status: 'repairing', repairUntilSimTime: sim.clockMs + REPAIR_DURATION_MS })
|
||||||
await inst.db.update(schema.account).set({ cash: Math.round((account.cash - cost) * 100) / 100 });
|
.where(eq(schema.planes.id, planeId));
|
||||||
}
|
await inst.db.update(schema.account).set({ cash: Math.round((account.cash - REPAIR_COST) * 100) / 100 });
|
||||||
await persist(inst);
|
await persist(inst);
|
||||||
return { cost };
|
return { cost: REPAIR_COST };
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Route helper (response convention, v0.8.0) ---
|
// --- Route helper (response convention, v0.8.0) ---
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import { FUEL_DISCOUNT_PER_REP, MAX_FUEL_DISCOUNT, MAX_PLANE_DISCOUNT, PLANE_DISCOUNT_PER_REP, PLANE_TYPES, repRate, STARTER_MODEL } from './catalog';
|
import { BROKEN_BURN_MULTIPLIER, conditionBurnMultiplier, FUEL_DISCOUNT_PER_REP, MAX_FUEL_DISCOUNT, MAX_PLANE_DISCOUNT, PLANE_DISCOUNT_PER_REP, PLANE_TYPES, repRate, STARTER_MODEL } from './catalog';
|
||||||
import { STARTING_REPUTATION } from './seed';
|
import { STARTING_REPUTATION } from './seed';
|
||||||
|
|
||||||
// v0.28.0 (ISS-047) — catalog sanity: the progression ladder must stay well-formed as types are added.
|
// v0.28.0 (ISS-047) — catalog sanity: the progression ladder must stay well-formed as types are added.
|
||||||
@@ -43,3 +43,21 @@ describe('repRate', () => {
|
|||||||
expect(repRate(1_000_000, FUEL_DISCOUNT_PER_REP, MAX_FUEL_DISCOUNT)).toBe(MAX_FUEL_DISCOUNT);
|
expect(repRate(1_000_000, FUEL_DISCOUNT_PER_REP, MAX_FUEL_DISCOUNT)).toBe(MAX_FUEL_DISCOUNT);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// v0.39.0 (ISS-069) — the broken-state burn factor: ×BROKEN_BURN_MULTIPLIER at/below zero health, exactly 1 above it.
|
||||||
|
describe('conditionBurnMultiplier', () => {
|
||||||
|
it('is exactly 1 for any positive health', () => {
|
||||||
|
expect(conditionBurnMultiplier(100)).toBe(1);
|
||||||
|
expect(conditionBurnMultiplier(42)).toBe(1);
|
||||||
|
expect(conditionBurnMultiplier(0.5)).toBe(1); // worn but not broken
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is exactly BROKEN_BURN_MULTIPLIER at and below zero health', () => {
|
||||||
|
expect(conditionBurnMultiplier(0)).toBe(BROKEN_BURN_MULTIPLIER);
|
||||||
|
expect(conditionBurnMultiplier(-3)).toBe(BROKEN_BURN_MULTIPLIER); // defensive — wear clamps at 0, but the gate is <= 0
|
||||||
|
});
|
||||||
|
|
||||||
|
it('pins the broken multiplier at ×1.5', () => {
|
||||||
|
expect(BROKEN_BURN_MULTIPLIER).toBe(1.5);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
+22
-2
@@ -100,7 +100,8 @@ export const PLANE_TYPES: Record<string, PlaneType> = {
|
|||||||
// The plane the player starts with.
|
// The plane the player starts with.
|
||||||
export const STARTER_MODEL = 'atr72';
|
export const STARTER_MODEL = 'atr72';
|
||||||
|
|
||||||
// Jet-A1 fuel price in €/liter (v0.8.0): refueling cost = (maxFuel − fuel) × this.
|
// Jet-A1 fuel price in €/liter (v0.8.0): top-up cost = liters × this — applied to the automatic
|
||||||
|
// dispatch top-ups since ISS-082 (manual refuel removed).
|
||||||
export const FUEL_PRICE_PER_L = 0.8;
|
export const FUEL_PRICE_PER_L = 0.8;
|
||||||
|
|
||||||
// Fraction of the catalog price paid out when selling a plane (v0.8.0).
|
// Fraction of the catalog price paid out when selling a plane (v0.8.0).
|
||||||
@@ -122,9 +123,28 @@ export const FUEL_DISCOUNT_PER_REP = 0.005;
|
|||||||
// ponytail: balance-tunable — max refuel price discount (reached at rep ≥ 50).
|
// ponytail: balance-tunable — max refuel price discount (reached at rep ≥ 50).
|
||||||
export const MAX_FUEL_DISCOUNT = 0.2;
|
export const MAX_FUEL_DISCOUNT = 0.2;
|
||||||
|
|
||||||
|
// --- Maintenance (v0.39.0, ISS-069) ---
|
||||||
|
|
||||||
|
// ponytail: balance-tunable — health lost per km of landed legs (~13 mid-range EDDF↔LEMD hops to break from full).
|
||||||
|
export const WEAR_PER_KM = 0.005;
|
||||||
|
|
||||||
|
// ponytail: balance-tunable — burn multiplier for a broken plane (health ≤ 0): it still flies, just thirsty.
|
||||||
|
export const BROKEN_BURN_MULTIPLIER = 1.5;
|
||||||
|
|
||||||
|
// Broken-state burn factor for one plane's health — the third multiplicative term alongside wind at every
|
||||||
|
// per-plane burn site (flyPlane dispatch top-up + backstop, engine landed fuel + auto-chain, live display).
|
||||||
|
export function conditionBurnMultiplier(health: number): number {
|
||||||
|
return health <= 0 ? BROKEN_BURN_MULTIPLIER : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ponytail: balance-tunable — flat repair cost in € (per-type if balance demands it).
|
||||||
|
export const REPAIR_COST = 1_500;
|
||||||
|
// ponytail: balance-tunable — how long a repair grounds the plane, sim ms (3 game days).
|
||||||
|
export const REPAIR_DURATION_MS = 3 * 86_400_000;
|
||||||
|
|
||||||
// Snapshot shape of one catalog entry in GET /api/state (v0.10.0): `model` is the
|
// Snapshot shape of one catalog entry in GET /api/state (v0.10.0): `model` is the
|
||||||
// id used by buy/dispatch, `label` the display name — clients compute all market
|
// id used by buy/dispatch, `label` the display name — clients compute all market
|
||||||
// previews (buy price, sell payout, refuel cost) from these + the economy constants.
|
// previews (buy price, sell payout) from these + the economy constants.
|
||||||
export interface CatalogEntry {
|
export interface CatalogEntry {
|
||||||
model: string;
|
model: string;
|
||||||
label: string;
|
label: string;
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ describe('buildSeed', () => {
|
|||||||
lat: 50.0333,
|
lat: 50.0333,
|
||||||
lon: 8.5706,
|
lon: 8.5706,
|
||||||
queue: [], // v0.25.0 (ISS-043) — no queued legs on first run
|
queue: [], // v0.25.0 (ISS-043) — no queued legs on first run
|
||||||
|
health: 100, // v0.39.0 (ISS-069) — full health on first run
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -42,6 +42,8 @@ export interface SeedPlane {
|
|||||||
// Upcoming legs not yet started (v0.25.0, ISS-043) — serialized to the queue
|
// 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.
|
// column as JSON text on insert; defaults to an empty queue.
|
||||||
queue?: string[];
|
queue?: string[];
|
||||||
|
// Structural health in [0, 100] (v0.39.0, ISS-069) — new planes start at full health.
|
||||||
|
health: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SeedPackage {
|
export interface SeedPackage {
|
||||||
@@ -237,6 +239,7 @@ export function buildSeed(input: {
|
|||||||
lat: hub.lat,
|
lat: hub.lat,
|
||||||
lon: hub.lon,
|
lon: hub.lon,
|
||||||
queue: [], // no queued legs on first run (v0.25.0)
|
queue: [], // no queued legs on first run (v0.25.0)
|
||||||
|
health: 100, // full health on first run (v0.39.0, ISS-069)
|
||||||
};
|
};
|
||||||
|
|
||||||
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));
|
||||||
|
|||||||
+14
-4
@@ -3,7 +3,7 @@ import { haversineKm, initialBearingDeg } from '@/lib/geo';
|
|||||||
import { weatherFor } from '@/lib/weather';
|
import { weatherFor } from '@/lib/weather';
|
||||||
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 { conditionBurnMultiplier, catalogEntries, FUEL_PRICE_PER_L, PLANE_TYPES, SELL_FRACTION, type CatalogEntry } from './catalog';
|
||||||
import { fuelAtWeighted, progressAt, positionAt, windBurnFactor } from '@/lib/sim/movement';
|
import { fuelAtWeighted, progressAt, positionAt, windBurnFactor } 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).
|
||||||
@@ -11,7 +11,8 @@ import { fuelAtWeighted, progressAt, positionAt, windBurnFactor } from '@/lib/si
|
|||||||
export interface PlaneState {
|
export interface PlaneState {
|
||||||
id: string;
|
id: string;
|
||||||
model: string;
|
model: string;
|
||||||
status: 'available' | 'flying';
|
// v0.39.0 (ISS-069): 'repairing' = grounded in the shop until repairUntilSimTime passes.
|
||||||
|
status: 'available' | 'flying' | 'repairing';
|
||||||
fuel: number;
|
fuel: number;
|
||||||
maxFuel: number;
|
maxFuel: number;
|
||||||
locationIcao: string;
|
locationIcao: string;
|
||||||
@@ -28,6 +29,11 @@ export interface PlaneState {
|
|||||||
// Upcoming legs NOT yet started (v0.25.0, ISS-043) — ordered ICAOs; the active
|
// 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.
|
// leg is destIcao. The engine auto-chains queue[0] on landing when fuel covers it.
|
||||||
queue: string[];
|
queue: string[];
|
||||||
|
// Structural health in [0, 100] (v0.39.0, ISS-069) — wears down with distance flown; at 0 the
|
||||||
|
// plane is broken and burns BROKEN_BURN_MULTIPLIER × more fuel until repaired.
|
||||||
|
health: number;
|
||||||
|
// Sim-clock epoch ms when an active repair finishes (v0.39.0, ISS-069); null when not in repair.
|
||||||
|
repairUntilSimTime: number | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse the planes.queue JSON column into an ICAO list (v0.25.0). Guards against
|
// Parse the planes.queue JSON column into an ICAO list (v0.25.0). Guards against
|
||||||
@@ -68,7 +74,7 @@ export interface StateSnapshot {
|
|||||||
planes: PlaneState[];
|
planes: PlaneState[];
|
||||||
packages: PackageState[];
|
packages: PackageState[];
|
||||||
// Market reference data (v0.10.0) — static per build, sent with every snapshot so
|
// Market reference data (v0.10.0) — static per build, sent with every snapshot so
|
||||||
// the client can compute buy/sell/refuel previews without a separate endpoint.
|
// the client can compute buy/sell previews without a separate endpoint.
|
||||||
catalog: CatalogEntry[];
|
catalog: CatalogEntry[];
|
||||||
fuelPricePerL: number;
|
fuelPricePerL: number;
|
||||||
sellFraction: number;
|
sellFraction: number;
|
||||||
@@ -107,10 +113,12 @@ export async function getStateSnapshot(): Promise<StateSnapshot> {
|
|||||||
const pos = positionAt(from.lat, from.lon, to.lat, to.lon, progress);
|
const pos = positionAt(from.lat, from.lon, to.lat, to.lon, progress);
|
||||||
// Wind-adjusted burn (v0.36.0) — weather is a pure function of the departure ICAO, so this
|
// Wind-adjusted burn (v0.36.0) — weather is a pure function of the departure ICAO, so this
|
||||||
// recomputes exactly the factor the engine used for the leg; no stored state needed.
|
// recomputes exactly the factor the engine used for the leg; no stored state needed.
|
||||||
|
// v0.39.0 (ISS-069): broken planes burn BROKEN_BURN_MULTIPLIER × more — p.health is frozen at
|
||||||
|
// departure (wear lands only), so this stays bit-consistent with the engine's landed fuel.
|
||||||
const w = weatherFor(p.locationIcao);
|
const w = weatherFor(p.locationIcao);
|
||||||
return { ...pos, fuel: fuelAtWeighted(
|
return { ...pos, fuel: fuelAtWeighted(
|
||||||
p.fuel,
|
p.fuel,
|
||||||
type.burnPerKm * windBurnFactor(w.windKt, w.windDirDeg, initialBearingDeg(from.lat, from.lon, to.lat, to.lon)),
|
type.burnPerKm * windBurnFactor(w.windKt, w.windDirDeg, initialBearingDeg(from.lat, from.lon, to.lat, to.lon)) * conditionBurnMultiplier(p.health),
|
||||||
type.emptyWeightKg,
|
type.emptyWeightKg,
|
||||||
type.maxFuel,
|
type.maxFuel,
|
||||||
distanceKm,
|
distanceKm,
|
||||||
@@ -140,6 +148,8 @@ export async function getStateSnapshot(): Promise<StateSnapshot> {
|
|||||||
lat: live?.lat ?? p.lat,
|
lat: live?.lat ?? p.lat,
|
||||||
lon: live?.lon ?? p.lon,
|
lon: live?.lon ?? p.lon,
|
||||||
queue: parseIcaoQueue(p.queue),
|
queue: parseIcaoQueue(p.queue),
|
||||||
|
health: p.health, // v0.39.0 (ISS-069) — stored value; wear accumulates at landing only
|
||||||
|
repairUntilSimTime: p.repairUntilSimTime,
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
packages: packageRows.map((p) => ({
|
packages: packageRows.map((p) => ({
|
||||||
|
|||||||
+56
-21
@@ -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, queue: [] },
|
{ 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, health: 100, repairUntilSimTime: null, 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, 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, health: 100, repairUntilSimTime: null, 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, queue: [] },
|
{ id: 'p1', model: 'mystery', status: 'available', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'x', destIcao: null, destName: null, departureSimTime: null, lat: 0, lon: 0, health: 100, repairUntilSimTime: null, 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, queue: [] },
|
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'x', destIcao: null, destName: null, departureSimTime: 0, lat: 0, lon: 0, health: 100, repairUntilSimTime: null, 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, queue: [] },
|
{ 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, health: 100, repairUntilSimTime: null, 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, queue: [] },
|
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', destIcao: 'EHAM', destName: 'A', departureSimTime: 0, lat: 51, lon: 9, health: 100, repairUntilSimTime: null, 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, queue: [] },
|
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'ZZZZ', locationName: '?', destIcao: 'EDDV', destName: 'H', departureSimTime: 0, lat: 0, lon: 0, health: 100, repairUntilSimTime: null, 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, queue: [] },
|
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', destIcao: 'EDDV', destName: 'H', departureSimTime: 0, lat: 51, lon: 9, health: 100, repairUntilSimTime: null, 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, 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, health: 100, repairUntilSimTime: null, queue: [] },
|
||||||
],
|
],
|
||||||
}),
|
}),
|
||||||
AIRPORTS,
|
AIRPORTS,
|
||||||
@@ -140,11 +140,37 @@ 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)', () => {
|
describe('queuedRoutesGeoJson (ISS-043 v0.26.0 — dotted queue line: dest → queued legs only; ISS-077 v0.41.0 — grounded queues too)', () => {
|
||||||
it('draws nothing for a grounded plane, even with a non-empty queue', () => {
|
it('grounded plane with a non-empty queue → one feature chaining locationIcao → queued legs (ISS-077)', () => {
|
||||||
const fc = queuedRoutesGeoJson(
|
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'] },
|
// Pre-built route while grounded: the line starts at the plane's current airport, not at any dest.
|
||||||
|
{ 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, health: 100, repairUntilSimTime: null, queue: ['EHAM'] },
|
||||||
|
],
|
||||||
|
AIRPORTS,
|
||||||
|
);
|
||||||
|
expect(fc.features).toHaveLength(1);
|
||||||
|
expect(fc.features[0].properties).toEqual({ planeId: 'p1' });
|
||||||
|
const coords = fc.features[0].geometry.coordinates;
|
||||||
|
expect(coords.length).toBe(ROUTE_ARC_SEGMENTS + 1); // one arc, exact endpoints
|
||||||
|
expect(coords[0]).toEqual([8.56, 50.03]); // starts at the plane's airport (EDDF)
|
||||||
|
expect(coords[coords.length - 1]).toEqual([4.76, 52.31]); // ends at the queued airport (EHAM)
|
||||||
|
});
|
||||||
|
|
||||||
|
it('skips a grounded plane whose locationIcao is missing from the airport index', () => {
|
||||||
|
const fc = queuedRoutesGeoJson(
|
||||||
|
[
|
||||||
|
{ id: 'p1', model: 'atr72', status: 'available', fuel: 1, maxFuel: 2, locationIcao: 'ZZZZ', locationName: '?', destIcao: null, destName: null, departureSimTime: null, lat: 0, lon: 0, health: 100, repairUntilSimTime: null, queue: ['EHAM'] },
|
||||||
|
],
|
||||||
|
AIRPORTS,
|
||||||
|
);
|
||||||
|
expect(fc.features).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('draws nothing for a repairing plane, even with a non-empty queue', () => {
|
||||||
|
const fc = queuedRoutesGeoJson(
|
||||||
|
[
|
||||||
|
{ id: 'p1', model: 'atr72', status: 'repairing', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', destIcao: null, destName: null, departureSimTime: null, lat: 50.03, lon: 8.56, health: 0, repairUntilSimTime: 1000, queue: ['EHAM'] },
|
||||||
],
|
],
|
||||||
AIRPORTS,
|
AIRPORTS,
|
||||||
);
|
);
|
||||||
@@ -154,7 +180,7 @@ describe('queuedRoutesGeoJson (ISS-043 v0.26.0 — dotted queue line: dest → q
|
|||||||
it('draws nothing for a flying plane with an empty queue', () => {
|
it('draws nothing for a flying plane with an empty queue', () => {
|
||||||
const fc = queuedRoutesGeoJson(
|
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: [] },
|
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', destIcao: 'EHAM', destName: 'A', departureSimTime: 0, lat: 51, lon: 9, health: 100, repairUntilSimTime: null, queue: [] },
|
||||||
],
|
],
|
||||||
AIRPORTS,
|
AIRPORTS,
|
||||||
);
|
);
|
||||||
@@ -165,7 +191,7 @@ describe('queuedRoutesGeoJson (ISS-043 v0.26.0 — dotted queue line: dest → q
|
|||||||
const fc = queuedRoutesGeoJson(
|
const fc = queuedRoutesGeoJson(
|
||||||
[
|
[
|
||||||
// Active leg EDDF→EHAM stays in routesGeoJson; the queue line is ONLY EHAM → EDDV → LEMD.
|
// 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'] },
|
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', destIcao: 'EHAM', destName: 'A', departureSimTime: 0, lat: 51, lon: 9, health: 100, repairUntilSimTime: null, queue: ['EDDV', 'LEMD'] },
|
||||||
],
|
],
|
||||||
AIRPORTS,
|
AIRPORTS,
|
||||||
);
|
);
|
||||||
@@ -182,24 +208,27 @@ describe('queuedRoutesGeoJson (ISS-043 v0.26.0 — dotted queue line: dest → q
|
|||||||
it('skips a plane whose dest or a queued ICAO is missing from the airport index', () => {
|
it('skips a plane whose dest or a queued ICAO is missing from the airport index', () => {
|
||||||
const fc = queuedRoutesGeoJson(
|
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: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', destIcao: 'ZZZZ', destName: '?', departureSimTime: 0, lat: 51, lon: 9, health: 100, repairUntilSimTime: null, 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'] },
|
{ id: 'p2', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', destIcao: 'EHAM', destName: 'A', departureSimTime: 0, lat: 51, lon: 9, health: 100, repairUntilSimTime: null, queue: ['ZZZZ'] },
|
||||||
],
|
],
|
||||||
AIRPORTS,
|
AIRPORTS,
|
||||||
);
|
);
|
||||||
expect(fc.features).toHaveLength(0);
|
expect(fc.features).toHaveLength(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('one feature per qualifying plane — grounded and empty-queue planes draw nothing', () => {
|
it('one feature per qualifying plane — flying and grounded queues draw; empty-queue planes do not', () => {
|
||||||
const fc = queuedRoutesGeoJson(
|
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: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', destIcao: 'EHAM', destName: 'A', departureSimTime: 0, lat: 51, lon: 9, health: 100, repairUntilSimTime: null, 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: '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, health: 100, repairUntilSimTime: null, 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'] },
|
{ 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, health: 100, repairUntilSimTime: null, queue: ['LEMD'] },
|
||||||
],
|
],
|
||||||
AIRPORTS,
|
AIRPORTS,
|
||||||
);
|
);
|
||||||
expect(fc.features.map((f) => f.properties.planeId)).toEqual(['p1']);
|
expect(fc.features.map((f) => f.properties.planeId)).toEqual(['p1', 'p3']); // p2 has an empty queue
|
||||||
|
const p3 = fc.features[1].geometry.coordinates;
|
||||||
|
expect(p3[0]).toEqual([9.68, 52.46]); // grounded chain starts at the plane's airport (EDDV)
|
||||||
|
expect(p3[p3.length - 1]).toEqual([-3.56, 40.47]); // …and ends at the queued airport (LEMD)
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -254,6 +283,12 @@ describe('hoverTraceGeoJson (ISS-040 v0.23.2 — on-board package trace from the
|
|||||||
it('returns an empty collection when the dest airport is missing from the dataset', () => {
|
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: [] });
|
expect(hoverTraceGeoJson({ lat: 0, lon: 0 }, 'ZZZZ', AIRPORTS)).toEqual({ type: 'FeatureCollection', features: [] });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ISS-077 (v0.41.0): a flying carrier's trace starts at its landing airport — when that IS the
|
||||||
|
// package's destination there is nothing to draw (the solid active-leg layer covers it).
|
||||||
|
it('returns an empty collection when the start point equals the dest airport', () => {
|
||||||
|
expect(hoverTraceGeoJson(AIRPORTS.get('EHAM')!, 'EHAM', AIRPORTS)).toEqual({ type: 'FeatureCollection', features: [] });
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('greatCircleArc (v0.12.2 — curved route traces)', () => {
|
describe('greatCircleArc (v0.12.2 — curved route traces)', () => {
|
||||||
|
|||||||
+20
-9
@@ -10,7 +10,8 @@ import { positionAt } from './sim/movement';
|
|||||||
export interface PlaneFeatureProps {
|
export interface PlaneFeatureProps {
|
||||||
id: string;
|
id: string;
|
||||||
modelLabel: string;
|
modelLabel: string;
|
||||||
status: 'available' | 'flying';
|
// v0.39.0 (ISS-069): 'repairing' planes render on the grounded layer (flying === false).
|
||||||
|
status: 'available' | 'flying' | 'repairing';
|
||||||
fuelText: string; // "1234 / 6300 L"
|
fuelText: string; // "1234 / 6300 L"
|
||||||
routeText: string; // "Origin → Destination" while flying, '' when grounded
|
routeText: string; // "Origin → Destination" while flying, '' when grounded
|
||||||
flying: boolean;
|
flying: boolean;
|
||||||
@@ -115,7 +116,10 @@ export function hoverRouteGeoJson(
|
|||||||
// ISS-040 (v0.23.2): the on-board package hover trace — same shape as hoverRouteGeoJson but the
|
// 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
|
// 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
|
// 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.
|
// collection when the destination is missing from the dataset — never guessed. ISS-077 (v0.41.0):
|
||||||
|
// also empty when the start point IS the destination airport itself (a flying carrier's trace now
|
||||||
|
// starts at its landing airport, which can equal the package's dest) — nothing to draw there; the
|
||||||
|
// solid active-leg layer covers that case.
|
||||||
export function hoverTraceGeoJson(
|
export function hoverTraceGeoJson(
|
||||||
from: AirportCoord,
|
from: AirportCoord,
|
||||||
toIcao: string,
|
toIcao: string,
|
||||||
@@ -123,6 +127,7 @@ export function hoverTraceGeoJson(
|
|||||||
): FeatureCollection<MapLineFeature> {
|
): FeatureCollection<MapLineFeature> {
|
||||||
const to = airportsByIcao.get(toIcao);
|
const to = airportsByIcao.get(toIcao);
|
||||||
if (!to) return EMPTY_LINES;
|
if (!to) return EMPTY_LINES;
|
||||||
|
if (from.lat === to.lat && from.lon === to.lon) return EMPTY_LINES; // start == dest — zero-length trace
|
||||||
return {
|
return {
|
||||||
type: 'FeatureCollection',
|
type: 'FeatureCollection',
|
||||||
features: [
|
features: [
|
||||||
@@ -165,19 +170,25 @@ 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
|
// ISS-043 (v0.26.0): the dotted queue line — one LineString per plane with a non-empty queue,
|
||||||
// queue, chaining dest → queue[0] → … → queue[n−1]: ONLY the not-yet-started legs (the active
|
// chaining the not-yet-started legs: a FLYING plane starts at its active leg's destination
|
||||||
// leg locationIcao→dest stays in routesGeoJson's solid layer). Arcs are concatenated with the
|
// (dest → queue[0] → …; the active leg locationIcao→dest stays in routesGeoJson's solid layer),
|
||||||
// shared joint point dropped once. A plane is skipped — never guessed — when its dest or any
|
// and ISS-077 (v0.41.0) extends it to GROUNDED ('available') planes, which start at their current
|
||||||
// queued ICAO is missing from the airport index; empty collection when nothing qualifies.
|
// airport (locationIcao → queue[0] → …). 'repairing' planes draw nothing — they can't fly. Arcs are
|
||||||
|
// concatenated with the shared joint point dropped once. A plane is skipped — never guessed — when
|
||||||
|
// its first point or any queued ICAO is missing from the airport index; empty collection when
|
||||||
|
// nothing qualifies.
|
||||||
export function queuedRoutesGeoJson(
|
export function queuedRoutesGeoJson(
|
||||||
planes: PlaneState[],
|
planes: PlaneState[],
|
||||||
airportsByIcao: ReadonlyMap<string, AirportCoord>,
|
airportsByIcao: ReadonlyMap<string, AirportCoord>,
|
||||||
): FeatureCollection<MapLineFeature> {
|
): FeatureCollection<MapLineFeature> {
|
||||||
const features: MapLineFeature[] = [];
|
const features: MapLineFeature[] = [];
|
||||||
for (const p of planes) {
|
for (const p of planes) {
|
||||||
if (p.status !== 'flying' || !p.destIcao || p.queue.length === 0) continue;
|
if (p.queue.length === 0) continue;
|
||||||
const pts = [p.destIcao, ...p.queue].map((icao) => airportsByIcao.get(icao));
|
// First point of the chain: a flying plane's landing airport, a grounded one's current airport.
|
||||||
|
const firstIcao = p.status === 'flying' ? p.destIcao : p.status === 'available' ? p.locationIcao : null;
|
||||||
|
if (!firstIcao) continue;
|
||||||
|
const pts = [firstIcao, ...p.queue].map((icao) => airportsByIcao.get(icao));
|
||||||
if (pts.some((c) => c === undefined)) continue; // an endpoint is missing from the dataset — skip
|
if (pts.some((c) => c === undefined)) continue; // an endpoint is missing from the dataset — skip
|
||||||
const coords: [number, number][] = [];
|
const coords: [number, number][] = [];
|
||||||
for (let i = 0; i < pts.length - 1; i++) {
|
for (let i = 0; i < pts.length - 1; i++) {
|
||||||
|
|||||||
+8
-15
@@ -14,7 +14,7 @@ describe('OpenAPI spec', () => {
|
|||||||
'/api/planes/{planeId}/fly',
|
'/api/planes/{planeId}/fly',
|
||||||
'/api/planes/{planeId}/queue', // v0.25.0 (ISS-043)
|
'/api/planes/{planeId}/queue', // v0.25.0 (ISS-043)
|
||||||
'/api/planes/{planeId}/queue/cancel', // v0.25.0 (ISS-043)
|
'/api/planes/{planeId}/queue/cancel', // v0.25.0 (ISS-043)
|
||||||
'/api/planes/{planeId}/refuel',
|
'/api/planes/{planeId}/repair', // v0.39.0 (ISS-069)
|
||||||
'/api/sim',
|
'/api/sim',
|
||||||
'/api/state',
|
'/api/state',
|
||||||
'/api/version',
|
'/api/version',
|
||||||
@@ -115,6 +115,7 @@ describe('OpenAPI spec', () => {
|
|||||||
'destIcao',
|
'destIcao',
|
||||||
'destName',
|
'destName',
|
||||||
'fuel',
|
'fuel',
|
||||||
|
'health', // v0.39.0 (ISS-069) — structural health in [0, 100]
|
||||||
'id',
|
'id',
|
||||||
'lat',
|
'lat',
|
||||||
'locationIcao',
|
'locationIcao',
|
||||||
@@ -123,6 +124,7 @@ describe('OpenAPI spec', () => {
|
|||||||
'maxFuel',
|
'maxFuel',
|
||||||
'model',
|
'model',
|
||||||
'queue', // v0.25.0 (ISS-043) — upcoming legs not yet started
|
'queue', // v0.25.0 (ISS-043) — upcoming legs not yet started
|
||||||
|
'repairUntilSimTime', // v0.39.0 (ISS-069) — active repair gate; null when not repairing
|
||||||
'status',
|
'status',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -192,7 +194,7 @@ describe('OpenAPI spec', () => {
|
|||||||
'/api/planes/{planeId}/queue/cancel', // 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}/repair', // v0.39.0 (ISS-069)
|
||||||
]) {
|
]) {
|
||||||
const ok = post(p).responses['200'] as { content: Record<string, { schema: { $ref: string } }> };
|
const ok = post(p).responses['200'] as { content: Record<string, { schema: { $ref: string } }> };
|
||||||
expect(ok.content['application/json'].schema.$ref).toBe('#/components/schemas/StateSnapshot');
|
expect(ok.content['application/json'].schema.$ref).toBe('#/components/schemas/StateSnapshot');
|
||||||
@@ -207,10 +209,9 @@ describe('OpenAPI spec', () => {
|
|||||||
expect(errorCodes('/api/planes/{planeId}/queue/cancel')).toEqual(['400', '404']); // v0.25.0
|
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(['400', '404', '409']); // v0.16.0 optional body
|
expect(errorCodes('/api/planes/{planeId}/repair')).toEqual(['404', '409']); // v0.39.0 (ISS-069) — no body, so no 400
|
||||||
|
|
||||||
// Request bodies: load/fly/buy/sell take their dedicated schemas; abandon takes none;
|
// Request bodies: load/fly/buy/sell take their dedicated schemas; abandon and repair take 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',
|
||||||
);
|
);
|
||||||
@@ -230,9 +231,7 @@ 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();
|
||||||
const refuelBody = post('/api/planes/{planeId}/refuel').requestBody;
|
expect(post('/api/planes/{planeId}/repair').requestBody).toBeUndefined(); // v0.39.0 (ISS-069) — no body, like abandon
|
||||||
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);
|
||||||
@@ -241,7 +240,7 @@ describe('OpenAPI spec', () => {
|
|||||||
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')).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}/queue/cancel')).toEqual(['planeId']); // v0.25.0 (ISS-043)
|
||||||
expect(paramNames('/api/planes/{planeId}/refuel')).toEqual(['planeId']);
|
expect(paramNames('/api/planes/{planeId}/repair')).toEqual(['planeId']); // v0.39.0 (ISS-069)
|
||||||
|
|
||||||
// Request schema shapes.
|
// Request schema shapes.
|
||||||
const load = openApiSpec.components.schemas.LoadPackageRequest;
|
const load = openApiSpec.components.schemas.LoadPackageRequest;
|
||||||
@@ -263,11 +262,5 @@ describe('OpenAPI spec', () => {
|
|||||||
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');
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+26
-43
@@ -8,7 +8,7 @@ export const openApiSpec = {
|
|||||||
info: {
|
info: {
|
||||||
title: 'Flight Ops API',
|
title: 'Flight Ops API',
|
||||||
description:
|
description:
|
||||||
'JSON API for Flight Ops — EU airport data for the map, the live game-state snapshot, player actions (load / fly / abandon / buy / sell / refuel), and app metadata. Every action endpoint ticks the sim clock first and returns the full state snapshot on success.',
|
'JSON API for Flight Ops — EU airport data for the map, the live game-state snapshot, player actions (load / fly / abandon / buy / sell), and app metadata. Every action endpoint ticks the sim clock first and returns the full state snapshot on success.',
|
||||||
// Sourced from package.json so it stays in sync with every version bump.
|
// Sourced from package.json so it stays in sync with every version bump.
|
||||||
version: pkg.version,
|
version: pkg.version,
|
||||||
},
|
},
|
||||||
@@ -37,7 +37,7 @@ export const openApiSpec = {
|
|||||||
get: {
|
get: {
|
||||||
summary: 'Game state snapshot',
|
summary: 'Game state snapshot',
|
||||||
description:
|
description:
|
||||||
'Full current game state for client polling — account, sim clock, planes and packages, plus the static market reference data (catalog + economy constants) so clients can compute buy/sell/refuel previews locally. Tick-on-read: each call first advances the sim clock by (real time since last read) × timeScale (clamped per tick), so expiry/delivery/spawn are always applied before the snapshot is returned.',
|
'Full current game state for client polling — account, sim clock, planes and packages, plus the static market reference data (catalog + economy constants) so clients can compute buy/sell previews locally. Tick-on-read: each call first advances the sim clock by (real time since last read) × timeScale (clamped per tick), so expiry/delivery/spawn are always applied before the snapshot is returned.',
|
||||||
operationId: 'getState',
|
operationId: 'getState',
|
||||||
responses: {
|
responses: {
|
||||||
200: {
|
200: {
|
||||||
@@ -194,7 +194,7 @@ export const openApiSpec = {
|
|||||||
post: {
|
post: {
|
||||||
summary: 'Fly a plane to an airport',
|
summary: 'Fly a plane to an airport',
|
||||||
description:
|
description:
|
||||||
'Manual flight (v0.12.0): send a GROUNDED ("available") plane to any known airport — its loaded packages\' destinations or pure repositioning. The plane becomes "flying" with departureSimTime = current sim clock and destIcao set; the engine flies it analytically, delivers bound cargo on arrival, and grounds it there.',
|
'Manual flight (v0.12.0): send a GROUNDED ("available") plane to any known airport — its loaded packages\' destinations or pure repositioning. The plane becomes "flying" with departureSimTime = current sim clock and destIcao set; the engine flies it analytically, delivers bound cargo on arrival, and grounds it there. ISS-082 (v0.42.0): dispatch auto-refuels first — the tank is topped up to min(maxFuel, max(fuel, 1.5 × required)) at fuelPricePerL per liter minus a reputation-scaled discount, deducted from cash; no separate refuel endpoint exists anymore.',
|
||||||
operationId: 'flyPlane',
|
operationId: 'flyPlane',
|
||||||
parameters: [
|
parameters: [
|
||||||
{ name: 'planeId', in: 'path', required: true, schema: { type: 'string' } },
|
{ name: 'planeId', in: 'path', required: true, schema: { type: 'string' } },
|
||||||
@@ -223,7 +223,7 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
409: {
|
409: {
|
||||||
description:
|
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)',
|
'Plane not grounded, or the leg does not fit even a FULL tank (v0.16.0 weight-proportional burn — the fuel required to cover the great-circle distance arriving empty; dispatch auto-refuels up to min(maxFuel, max(fuel, 1.5 × required)) first, ISS-082), or cash is insufficient for that top-up',
|
||||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -233,7 +233,7 @@ export const openApiSpec = {
|
|||||||
post: {
|
post: {
|
||||||
summary: 'Queue a flight leg for a plane',
|
summary: 'Queue a flight leg for a plane',
|
||||||
description:
|
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).',
|
'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 — with a short tank it auto-refuels to 150% of the requirement (capped at tank capacity) when cash allows (ISS-082); only an unaffordable top-up grounds the plane with the queue kept intact for a later dispatch.',
|
||||||
operationId: 'queueLeg',
|
operationId: 'queueLeg',
|
||||||
parameters: [
|
parameters: [
|
||||||
{ name: 'planeId', in: 'path', required: true, schema: { type: 'string' } },
|
{ name: 'planeId', in: 'path', required: true, schema: { type: 'string' } },
|
||||||
@@ -366,39 +366,26 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
'/api/planes/{planeId}/refuel': {
|
'/api/planes/{planeId}/repair': {
|
||||||
post: {
|
post: {
|
||||||
summary: 'Refuel a grounded plane',
|
summary: 'Repair a grounded plane',
|
||||||
description:
|
description:
|
||||||
'Refuel a grounded plane at the fuel price per added liter, deducted from cash (v0.8.0); the per-liter price is reduced by a reputation-scaled discount (v0.38.0, ISS-072 — higher reputation refuels cheaper; no discount at the starting reputation). The body is optional (v0.16.0): no body or mode "full" fills to maxFuel; mode "forFlight" with packageId buys 150% of the weather-adjusted fuel required for that loaded package\'s destination leg, capped at tank capacity — liters = min(maxFuel, max(current fuel, 1.5 × required)) − current fuel, where required is the weight-proportional burn model over the great-circle distance with a ±20% wind adjustment (v0.36.0).',
|
'Restore a worn-out plane to full health for the flat repair cost (v0.39.0, ISS-069): the plane is grounded in "repairing" status until 3 sim days pass, when the engine\'s tick flips it back to "available". While repairing it cannot load, fly or be sold; a broken plane (health ≤ 0) still flies but burns 50% more fuel. A full-health repair is a free no-op (cost 0). No body.',
|
||||||
operationId: 'refuelPlane',
|
operationId: 'repairPlane',
|
||||||
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 raised by exactly the added liters, cash reduced by the cost)',
|
description: 'Repair started (or free no-op) — full state snapshot (health 100, status "repairing" with the gate set, cash reduced by the flat 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 (or unknown package id in forFlight mode)',
|
description: 'Unknown plane id',
|
||||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||||
},
|
},
|
||||||
409: {
|
409: {
|
||||||
description:
|
description: 'Plane is not grounded (flying or already repairing), or cash is insufficient for the repair cost',
|
||||||
'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' } } },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -476,7 +463,7 @@ export const openApiSpec = {
|
|||||||
description: 'Aircraft catalog (v0.10.0) — static per build, one entry per plane type.',
|
description: 'Aircraft catalog (v0.10.0) — static per build, one entry per plane type.',
|
||||||
items: { $ref: '#/components/schemas/CatalogEntry' },
|
items: { $ref: '#/components/schemas/CatalogEntry' },
|
||||||
},
|
},
|
||||||
fuelPricePerL: { type: 'number', description: 'Jet-A1 price in €/liter; refuel cost = (maxFuel − fuel) × this, reduced by a reputation-scaled discount at refuel time (v0.38.0).' },
|
fuelPricePerL: { type: 'number', description: 'Jet-A1 price in €/liter; the automatic dispatch top-up costs liters × this, reduced by a reputation-scaled discount at refuel time (v0.38.0) — ISS-082 (v0.42.0): it now applies to the auto-refuel on /fly and the engine\'s chained-leg top-ups.' },
|
||||||
sellFraction: { type: 'number', description: 'Fraction of the catalog price paid out when selling a plane.' },
|
sellFraction: { type: 'number', description: 'Fraction of the catalog price paid out when selling a plane.' },
|
||||||
},
|
},
|
||||||
required: ['account', 'simState', 'planes', 'packages', 'catalog', 'fuelPricePerL', 'sellFraction'],
|
required: ['account', 'simState', 'planes', 'packages', 'catalog', 'fuelPricePerL', 'sellFraction'],
|
||||||
@@ -567,22 +554,6 @@ 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" buys 150% of the weather-adjusted fuel required for one loaded package\'s destination leg, capped at tank capacity (v0.36.0).',
|
|
||||||
},
|
|
||||||
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: {
|
||||||
@@ -595,7 +566,7 @@ export const openApiSpec = {
|
|||||||
properties: {
|
properties: {
|
||||||
id: { type: 'string' },
|
id: { type: 'string' },
|
||||||
model: { type: 'string' },
|
model: { type: 'string' },
|
||||||
status: { enum: ['available', 'flying'] },
|
status: { enum: ['available', 'flying', 'repairing'] }, // v0.39.0 (ISS-069) — "repairing" = grounded in the shop until repairUntilSimTime passes
|
||||||
fuel: { type: 'number' },
|
fuel: { type: 'number' },
|
||||||
maxFuel: { type: 'number' },
|
maxFuel: { type: 'number' },
|
||||||
locationIcao: { type: 'string' },
|
locationIcao: { type: 'string' },
|
||||||
@@ -620,6 +591,16 @@ export const openApiSpec = {
|
|||||||
description:
|
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.',
|
'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.',
|
||||||
},
|
},
|
||||||
|
health: {
|
||||||
|
type: 'number',
|
||||||
|
description:
|
||||||
|
'Structural health in [0, 100] (v0.39.0) — wears down by a fixed amount per km of landed legs; at 0 the plane is broken and burns 50% more fuel until repaired.',
|
||||||
|
},
|
||||||
|
repairUntilSimTime: {
|
||||||
|
type: ['integer', 'null'],
|
||||||
|
description:
|
||||||
|
'Sim-clock epoch ms when an active repair finishes (v0.39.0) — set with status "repairing", cleared by the engine\'s flip-back; null when not in repair.',
|
||||||
|
},
|
||||||
},
|
},
|
||||||
required: [
|
required: [
|
||||||
'id',
|
'id',
|
||||||
@@ -635,6 +616,8 @@ export const openApiSpec = {
|
|||||||
'lat',
|
'lat',
|
||||||
'lon',
|
'lon',
|
||||||
'queue',
|
'queue',
|
||||||
|
'health', // v0.39.0 (ISS-069) — structural health in [0, 100]
|
||||||
|
'repairUntilSimTime', // v0.39.0 (ISS-069) — active repair gate; null when not repairing
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
PackageState: {
|
PackageState: {
|
||||||
|
|||||||
+167
-9
@@ -8,7 +8,7 @@ import * as schema from '@/lib/db/schema';
|
|||||||
import { loadAirportsGeoJson } from '@/lib/airports';
|
import { loadAirportsGeoJson } from '@/lib/airports';
|
||||||
import { haversineKm, initialBearingDeg } from '@/lib/geo';
|
import { haversineKm, initialBearingDeg } from '@/lib/geo';
|
||||||
import { weatherFor } from '@/lib/weather';
|
import { weatherFor } from '@/lib/weather';
|
||||||
import { PLANE_TYPES } from '@/lib/game/catalog';
|
import { BROKEN_BURN_MULTIPLIER, conditionBurnMultiplier, FUEL_DISCOUNT_PER_REP, FUEL_PRICE_PER_L, MAX_FUEL_DISCOUNT, PLANE_TYPES, repRate, WEAR_PER_KM } from '@/lib/game/catalog';
|
||||||
import { SPECIALS } from '@/lib/game/specials';
|
import { SPECIALS } from '@/lib/game/specials';
|
||||||
import { MARKET_TARGET_OPEN_PACKAGES, mulberry32 } from '@/lib/game/seed';
|
import { MARKET_TARGET_OPEN_PACKAGES, mulberry32 } from '@/lib/game/seed';
|
||||||
import { arrivalTimeFor, fuelAtWeighted, requiredFuelFor, windBurnFactor } from './movement';
|
import { arrivalTimeFor, fuelAtWeighted, requiredFuelFor, windBurnFactor } from './movement';
|
||||||
@@ -16,6 +16,7 @@ import {
|
|||||||
clampTimeScale,
|
clampTimeScale,
|
||||||
deliverPackages,
|
deliverPackages,
|
||||||
expirePackages,
|
expirePackages,
|
||||||
|
finishRepairs,
|
||||||
MAX_TICK_ELAPSED_MS,
|
MAX_TICK_ELAPSED_MS,
|
||||||
MAX_TIME_SCALE,
|
MAX_TIME_SCALE,
|
||||||
MIN_TIME_SCALE,
|
MIN_TIME_SCALE,
|
||||||
@@ -297,19 +298,65 @@ describe('deliverPackages (v0.12.0 arrival delivery)', () => {
|
|||||||
expect(JSON.parse(plane.queue)).toEqual(['EDDV']); // first leg consumed, rest kept in order
|
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 () => {
|
it('auto-refuels a short tank and chains the next queued leg when cash allows (ISS-082)', async () => {
|
||||||
const { inst, from, to, km, type } = await setupFlight('chain-nofuel.db');
|
const { inst, from, to, km, type } = await setupFlight('chain-autorefuel.db');
|
||||||
|
|
||||||
// Depart with exactly the wind-adjusted fuel for EDDF→LEMD (v0.36.0) → lands empty, cannot start LEMD→EHAM.
|
// Depart with exactly the wind-adjusted fuel for EDDF→LEMD (v0.36.0) → lands empty; the LEMD→EHAM hop needs a top-up.
|
||||||
const w = weatherFor(FROM);
|
const w = weatherFor(FROM);
|
||||||
const f = windBurnFactor(w.windKt, w.windDirDeg, initialBearingDeg(from.lat, from.lon, to.lat, to.lon));
|
const f = windBurnFactor(w.windKt, w.windDirDeg, initialBearingDeg(from.lat, from.lon, to.lat, to.lon));
|
||||||
|
const depFuel = requiredFuelFor(type.burnPerKm * f, type.emptyWeightKg, type.maxFuel, km);
|
||||||
await inst.db.update(schema.planes)
|
await inst.db.update(schema.planes)
|
||||||
.set({
|
.set({ fuel: depFuel, queue: JSON.stringify(['EHAM']) })
|
||||||
fuel: requiredFuelFor(type.burnPerKm * f, type.emptyWeightKg, type.maxFuel, km),
|
|
||||||
queue: JSON.stringify(['EHAM']),
|
|
||||||
})
|
|
||||||
.where(eq(schema.planes.id, 'plane-starter'));
|
.where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
|
const accountBefore = (await inst.db.select().from(schema.account))[0]!; // seeded €20k — the top-up is affordable
|
||||||
|
const clock = T0 + travelMs(km, type.speedKmh); // exactly at arrival
|
||||||
|
expect(await deliverPackages(inst, clock)).toBe(1);
|
||||||
|
|
||||||
|
// Expected top-up from the SAME helpers the engine uses: landed fuel (≈ 0), post-wear health,
|
||||||
|
// wind-adjusted requirement for LEMD→EHAM, ×1.5 margin capped at tank capacity.
|
||||||
|
const fc = await loadAirportsGeoJson();
|
||||||
|
const nextP = fc.features.find((x) => x.properties.icao === 'EHAM')!.properties;
|
||||||
|
const landedFuel = fuelAtWeighted(depFuel, type.burnPerKm * f, type.emptyWeightKg, type.maxFuel, km, 1);
|
||||||
|
expect(landedFuel).toBeCloseTo(0, 6); // sanity: arrived empty — the top-up path is what ran
|
||||||
|
const newHealth = Math.max(0, 100 - WEAR_PER_KM * km);
|
||||||
|
const wTo = weatherFor(TO); // the chained leg departs from the arrival airport
|
||||||
|
const fNext = windBurnFactor(wTo.windKt, wTo.windDirDeg, initialBearingDeg(to.lat, to.lon, nextP.lat, nextP.lon));
|
||||||
|
const nextRequiredL = requiredFuelFor(
|
||||||
|
type.burnPerKm * fNext * conditionBurnMultiplier(newHealth),
|
||||||
|
type.emptyWeightKg,
|
||||||
|
type.maxFuel,
|
||||||
|
haversineKm(to.lat, to.lon, nextP.lat, nextP.lon),
|
||||||
|
);
|
||||||
|
const target = Math.min(type.maxFuel, Math.max(landedFuel, nextRequiredL * 1.5));
|
||||||
|
const liters = Math.max(0, target - landedFuel);
|
||||||
|
expect(liters).toBeGreaterThan(0); // the hop genuinely needs more than what's left
|
||||||
|
const rate = repRate(accountBefore.reputation, FUEL_DISCOUNT_PER_REP, MAX_FUEL_DISCOUNT);
|
||||||
|
const expectedCost = Math.round(liters * FUEL_PRICE_PER_L * (1 - rate) * 100) / 100;
|
||||||
|
|
||||||
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
|
expect(plane.status).toBe('flying'); // chained — the top-up funded it…
|
||||||
|
expect(plane.destIcao).toBe('EHAM');
|
||||||
|
expect(plane.departureSimTime).toBe(clock);
|
||||||
|
expect(JSON.parse(plane.queue)).toEqual([]); // …leg consumed, rest kept in order
|
||||||
|
expect(plane.fuel).toBeCloseTo(target, 6); // …departing with the post-top-up level
|
||||||
|
|
||||||
|
const account = (await inst.db.select().from(schema.account))[0]!;
|
||||||
|
expect(account.cash).toBeCloseTo(accountBefore.cash - expectedCost, 9); // exactly the rep-discounted cost
|
||||||
|
});
|
||||||
|
|
||||||
|
it('grounds with the queue intact when cash cannot cover the auto top-up (ISS-082)', async () => {
|
||||||
|
const { inst, from, to, km, type } = await setupFlight('chain-nofuel-poor.db');
|
||||||
|
|
||||||
|
// Same empty-tank landing as above, but the account is broke — the top-up is unaffordable.
|
||||||
|
const w = weatherFor(FROM);
|
||||||
|
const f = windBurnFactor(w.windKt, w.windDirDeg, initialBearingDeg(from.lat, from.lon, to.lat, to.lon));
|
||||||
|
const depFuel = requiredFuelFor(type.burnPerKm * f, type.emptyWeightKg, type.maxFuel, km);
|
||||||
|
await inst.db.update(schema.planes)
|
||||||
|
.set({ fuel: depFuel, queue: JSON.stringify(['EHAM']) })
|
||||||
|
.where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
await inst.db.update(schema.account).set({ cash: 0 });
|
||||||
|
|
||||||
const clock = T0 + travelMs(km, type.speedKmh); // exactly at arrival
|
const clock = T0 + travelMs(km, type.speedKmh); // exactly at arrival
|
||||||
expect(await deliverPackages(inst, clock)).toBe(1);
|
expect(await deliverPackages(inst, clock)).toBe(1);
|
||||||
|
|
||||||
@@ -317,7 +364,10 @@ describe('deliverPackages (v0.12.0 arrival delivery)', () => {
|
|||||||
expect(plane.status).toBe('available'); // grounded safely…
|
expect(plane.status).toBe('available'); // grounded safely…
|
||||||
expect(plane.destIcao).toBeNull();
|
expect(plane.destIcao).toBeNull();
|
||||||
expect(plane.departureSimTime).toBeNull();
|
expect(plane.departureSimTime).toBeNull();
|
||||||
expect(JSON.parse(plane.queue)).toEqual(['EHAM']); // …queue kept for refuel + re-dispatch
|
expect(JSON.parse(plane.queue)).toEqual(['EHAM']); // …queue kept for a later dispatch
|
||||||
|
const landedFuel = fuelAtWeighted(depFuel, type.burnPerKm * f, type.emptyWeightKg, type.maxFuel, km, 1);
|
||||||
|
expect(plane.fuel).toBeCloseTo(landedFuel, 6); // no top-up happened — the tank is untouched
|
||||||
|
expect((await inst.db.select().from(schema.account))[0]!.cash).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('grounds as before when the queue is empty', async () => {
|
it('grounds as before when the queue is empty', async () => {
|
||||||
@@ -331,6 +381,114 @@ describe('deliverPackages (v0.12.0 arrival delivery)', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('wear on landed legs + broken burn (v0.39.0, ISS-069)', () => {
|
||||||
|
const FROM = 'EDDF';
|
||||||
|
const TO = 'LEMD';
|
||||||
|
|
||||||
|
// Starter flying EDDF→LEMD with a full tank — same shape as the deliverPackages setup above.
|
||||||
|
async function setupFlight(name: string) {
|
||||||
|
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.planes)
|
||||||
|
.set({ status: 'flying', destIcao: TO, departureSimTime: T0, fuel: type.maxFuel })
|
||||||
|
.where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
|
return { inst, from, to, km, type };
|
||||||
|
}
|
||||||
|
|
||||||
|
it('drops health by exactly WEAR_PER_KM × km on a landed leg', async () => {
|
||||||
|
const { inst, km } = await setupFlight('wear-leg.db');
|
||||||
|
|
||||||
|
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.health).toBeCloseTo(100 - WEAR_PER_KM * km, 9); // one mid-range hop ≈ −9.8 health
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clamps at 0 across multiple legs', async () => {
|
||||||
|
const { inst, from, to, km, type } = await setupFlight('wear-clamp.db');
|
||||||
|
// Start below one leg's wear so the first landing clamps…
|
||||||
|
await inst.db.update(schema.planes)
|
||||||
|
.set({ health: WEAR_PER_KM * km / 2 })
|
||||||
|
.where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
|
expect(await deliverPackages(inst, T0 + travelMs(km, type.speedKmh))).toBe(1);
|
||||||
|
let plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
|
expect(plane.health).toBe(0); // clamped — never negative…
|
||||||
|
|
||||||
|
// …and a second leg keeps it pinned at 0.
|
||||||
|
const eham = (await loadAirportsGeoJson()).features.find((f) => f.properties.icao === 'EHAM')!.properties;
|
||||||
|
const nextKm = haversineKm(to.lat, to.lon, eham.lat, eham.lon);
|
||||||
|
await inst.db.update(schema.planes)
|
||||||
|
.set({ status: 'flying', destIcao: 'EHAM', departureSimTime: T0 + travelMs(km, type.speedKmh), fuel: type.maxFuel })
|
||||||
|
.where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
|
expect(await deliverPackages(inst, T0 + travelMs(km, type.speedKmh) + travelMs(nextKm, type.speedKmh))).toBe(1);
|
||||||
|
plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
|
expect(plane.health).toBe(0); // still clamped after the second leg
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a broken plane burns ×1.5 more fuel on the leg (landed fuel)', async () => {
|
||||||
|
const { inst, from, to, km, type } = await setupFlight('wear-broken.db');
|
||||||
|
await inst.db.update(schema.planes).set({ health: 0 }).where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
|
expect(await deliverPackages(inst, T0 + travelMs(km, type.speedKmh))).toBe(1);
|
||||||
|
|
||||||
|
const w = weatherFor(FROM);
|
||||||
|
const f = windBurnFactor(w.windKt, w.windDirDeg, initialBearingDeg(from.lat, from.lon, to.lat, to.lon));
|
||||||
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
|
// The ×1.5-adjusted closed form — the same factor livePlane() shows in flight…
|
||||||
|
expect(plane.fuel).toBeCloseTo(
|
||||||
|
fuelAtWeighted(type.maxFuel, type.burnPerKm * f * BROKEN_BURN_MULTIPLIER, type.emptyWeightKg, type.maxFuel, km, 1),
|
||||||
|
6,
|
||||||
|
);
|
||||||
|
|
||||||
|
// …and strictly less than the healthy control on the identical leg.
|
||||||
|
const control = await setupFlight('wear-broken-control.db');
|
||||||
|
expect(await deliverPackages(control.inst, T0 + travelMs(km, type.speedKmh))).toBe(1);
|
||||||
|
const healthy = (await control.inst.db.select().from(schema.planes))[0];
|
||||||
|
expect(healthy.fuel).toBeCloseTo(fuelAtWeighted(type.maxFuel, type.burnPerKm * f, type.emptyWeightKg, type.maxFuel, km, 1), 6);
|
||||||
|
expect(plane.fuel).toBeLessThan(healthy.fuel); // the broken plane genuinely burned more
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('finishRepairs (v0.39.0, ISS-069)', () => {
|
||||||
|
it('flips repairing planes back to available once the gate passes, clearing the gate', async () => {
|
||||||
|
const inst = await freshDb('repair-finish.db');
|
||||||
|
await inst.db.update(schema.planes)
|
||||||
|
.set({ status: 'repairing', repairUntilSimTime: T0 + 5_000 })
|
||||||
|
.where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
|
expect(await finishRepairs(inst, T0 + 4_999)).toBe(0); // gate not reached yet…
|
||||||
|
let plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
|
expect(plane.status).toBe('repairing');
|
||||||
|
|
||||||
|
expect(await finishRepairs(inst, T0 + 5_000)).toBe(1); // <= is inclusive at the clock
|
||||||
|
plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
|
expect(plane.status).toBe('available');
|
||||||
|
expect(plane.repairUntilSimTime ?? null).toBeNull(); // gate cleared
|
||||||
|
});
|
||||||
|
|
||||||
|
it('runs inside tickOnce even when nothing landed: a past gate flips the plane back', async () => {
|
||||||
|
const inst = await freshDb('repair-tick.db');
|
||||||
|
await inst.db.update(schema.planes)
|
||||||
|
.set({ status: 'repairing', repairUntilSimTime: T0 + 1_500 })
|
||||||
|
.where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
|
vi.setSystemTime(T0 + 2_000); // one clamped tick at scale 1 → clock T0+2000 ≥ gate; nothing is flying
|
||||||
|
await tickOnce(inst);
|
||||||
|
|
||||||
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
|
expect(plane.status).toBe('available');
|
||||||
|
expect(plane.repairUntilSimTime ?? null).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('slow to 1× when a landing leaves any plane on the ground (ISS-057)', () => {
|
describe('slow to 1× when a landing leaves any plane on the ground (ISS-057)', () => {
|
||||||
const FROM = 'EDDF';
|
const FROM = 'EDDF';
|
||||||
const TO = 'LEMD';
|
const TO = 'LEMD';
|
||||||
|
|||||||
+57
-10
@@ -5,7 +5,7 @@ import * as schema from '@/lib/db/schema';
|
|||||||
import { loadAirportsGeoJson } from '@/lib/airports';
|
import { loadAirportsGeoJson } from '@/lib/airports';
|
||||||
import { haversineKm, initialBearingDeg } from '@/lib/geo';
|
import { haversineKm, initialBearingDeg } from '@/lib/geo';
|
||||||
import { weatherFor } from '@/lib/weather';
|
import { weatherFor } from '@/lib/weather';
|
||||||
import { PLANE_TYPES } from '@/lib/game/catalog';
|
import { conditionBurnMultiplier, FUEL_DISCOUNT_PER_REP, FUEL_PRICE_PER_L, MAX_FUEL_DISCOUNT, PLANE_TYPES, repRate, WEAR_PER_KM } from '@/lib/game/catalog';
|
||||||
import { SPECIALS } from '@/lib/game/specials';
|
import { SPECIALS } from '@/lib/game/specials';
|
||||||
import { parseIcaoQueue } from '@/lib/game/state';
|
import { parseIcaoQueue } from '@/lib/game/state';
|
||||||
import {
|
import {
|
||||||
@@ -79,6 +79,9 @@ export async function tickOnce(inst: GameDb): Promise<schema.SimStateRow> {
|
|||||||
await expirePackages(inst, clockMs);
|
await expirePackages(inst, clockMs);
|
||||||
// ISS-057: remember the landings so the tick can slow down when a plane is left on ground.
|
// ISS-057: remember the landings so the tick can slow down when a plane is left on ground.
|
||||||
landedThisTick = await deliverPackages(inst, clockMs);
|
landedThisTick = await deliverPackages(inst, clockMs);
|
||||||
|
// v0.39.0 (ISS-069): repairs whose gate has passed flip back to 'available' — runs even when
|
||||||
|
// nothing landed this tick; BEFORE the spawns so a just-repaired plane gets coverage work too.
|
||||||
|
await finishRepairs(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.
|
||||||
@@ -126,14 +129,33 @@ export async function expirePackages(inst: GameDb, clockMs: number): Promise<num
|
|||||||
return n;
|
return n;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Repairs whose gate has passed flip the plane back to 'available' and clear the gate
|
||||||
|
// (v0.39.0, ISS-069) — same shape as expirePackages: one guarded pass over the rows,
|
||||||
|
// `<=` inclusive at the clock. Returns the count flipped.
|
||||||
|
export async function finishRepairs(inst: GameDb, clockMs: number): Promise<number> {
|
||||||
|
const rows = await inst.db.select().from(schema.planes).where(eq(schema.planes.status, 'repairing'));
|
||||||
|
let n = 0;
|
||||||
|
for (const p of rows) {
|
||||||
|
if (p.repairUntilSimTime !== null && p.repairUntilSimTime <= clockMs) {
|
||||||
|
await inst.db.update(schema.planes)
|
||||||
|
.set({ status: 'available', repairUntilSimTime: null })
|
||||||
|
.where(eq(schema.planes.id, p.id));
|
||||||
|
n++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
// 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):
|
||||||
// for every package bound to the plane and destined for its dest_icao — 'loaded'
|
// for every package bound to the plane and destined for its dest_icao — 'loaded'
|
||||||
// ones still inside their deadline are delivered (cash += reward + reputation
|
// ones still inside their deadline are delivered (cash += reward + reputation
|
||||||
// gain per package), 'expired' ones just unbind (no reward). Packages destined
|
// gain per package), 'expired' ones just unbind (no reward). Packages destined
|
||||||
// elsewhere stay loaded on the plane for a later leg. Then (v0.25.0, ISS-043)
|
// elsewhere stay loaded on the plane for a later leg. Then (v0.25.0, ISS-043)
|
||||||
// auto-chain: if the queue holds legs and fuel covers the first one, start it
|
// auto-chain: if the queue holds legs and fuel covers the first one, start it
|
||||||
// immediately from the arrival airport; otherwise ground the plane there with
|
// immediately from the arrival airport; with a short tank, ISS-082 (v0.42.0) tops
|
||||||
// its remaining fuel (a short tank keeps the queue intact for refuel + re-dispatch).
|
// up to 150% of the requirement (capped at tank capacity) when cash allows and
|
||||||
|
// chains anyway — only an unaffordable top-up grounds the plane there with its
|
||||||
|
// remaining fuel and the queue kept intact for a later dispatch.
|
||||||
// Idempotent — a finalized plane either leaves the 'flying' state or starts a NEW
|
// 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.
|
// 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 —
|
// Returns planes landed. NOTE: runs BEFORE tickOnce's slow-down check on purpose —
|
||||||
@@ -160,16 +182,21 @@ export async function deliverPackages(inst: GameDb, clockMs: number): Promise<nu
|
|||||||
|
|
||||||
// Arrived: progress is exactly 1 here, so remaining fuel is the full-leg weighted burn —
|
// Arrived: progress is exactly 1 here, so remaining fuel is the full-leg weighted burn —
|
||||||
// wind-adjusted (v0.36.0) by departure weather vs route heading, same factor flyPlane used.
|
// wind-adjusted (v0.36.0) by departure weather vs route heading, same factor flyPlane used.
|
||||||
|
// v0.39.0 (ISS-069): broken planes (health ≤ 0 at DEPARTURE) burn BROKEN_BURN_MULTIPLIER × more —
|
||||||
|
// p.health is the pre-landing value, so this stays bit-consistent with livePlane()'s gauge.
|
||||||
const w = weatherFor(p.locationIcao);
|
const w = weatherFor(p.locationIcao);
|
||||||
const landedFuel = fuelAtWeighted(
|
const landedFuel = fuelAtWeighted(
|
||||||
p.fuel,
|
p.fuel,
|
||||||
type.burnPerKm * windBurnFactor(w.windKt, w.windDirDeg, initialBearingDeg(from.lat, from.lon, to.lat, to.lon)),
|
type.burnPerKm * windBurnFactor(w.windKt, w.windDirDeg, initialBearingDeg(from.lat, from.lon, to.lat, to.lon)) * conditionBurnMultiplier(p.health),
|
||||||
type.emptyWeightKg,
|
type.emptyWeightKg,
|
||||||
type.maxFuel,
|
type.maxFuel,
|
||||||
distanceKm,
|
distanceKm,
|
||||||
1,
|
1,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Wear (v0.39.0, ISS-069): health drops by WEAR_PER_KM per km of this landed leg, clamped at 0.
|
||||||
|
const newHealth = Math.max(0, p.health - WEAR_PER_KM * distanceKm);
|
||||||
|
|
||||||
// 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).
|
// 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);
|
||||||
@@ -194,19 +221,23 @@ export async function deliverPackages(inst: GameDb, clockMs: number): Promise<nu
|
|||||||
|
|
||||||
// Auto-chain (ISS-043): with a non-empty queue and enough fuel for the first
|
// 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
|
// queued leg, start it immediately from `to` — same feasibility rule as flyPlane
|
||||||
// (requiredFuelFor is independent of current load). Otherwise ground here; an
|
// (requiredFuelFor is independent of current load). ISS-082 (v0.42.0): manual refuel is gone,
|
||||||
// unknown ICAO in the queue simply cannot chain. The remaining queue is kept
|
// so a short tank no longer strands the chain — when cash allows, top up to 150% of the
|
||||||
// intact either way so a grounded plane can refuel and re-dispatch.
|
// requirement (capped at tank capacity) and chain anyway; unaffordable → ground here with the
|
||||||
|
// queue kept intact. An unknown ICAO in the queue simply cannot chain either way.
|
||||||
const queue = parseIcaoQueue(p.queue);
|
const queue = parseIcaoQueue(p.queue);
|
||||||
let chainedTo: string | null = null;
|
let chainedTo: string | null = null;
|
||||||
|
let topUpFuel: number | null = null; // post-top-up fuel for the chained departure, when a top-up happened
|
||||||
if (queue.length > 0) {
|
if (queue.length > 0) {
|
||||||
const nextDest = queue[0];
|
const nextDest = queue[0];
|
||||||
const next = byIcao.get(nextDest); // unknown ICAO in the queue → cannot chain
|
const next = byIcao.get(nextDest); // unknown ICAO in the queue → cannot chain
|
||||||
if (next) {
|
if (next) {
|
||||||
// Wind-adjusted requirement for the NEXT leg — it departs from `to` (v0.36.0).
|
// Wind-adjusted requirement for the NEXT leg — it departs from `to` (v0.36.0). v0.39.0 (ISS-069):
|
||||||
|
// the chained leg starts AFTER this landing's wear, so its burn uses newHealth — exactly what
|
||||||
|
// livePlane()/the next landing will compute for that flight.
|
||||||
const wNext = weatherFor(to.icao);
|
const wNext = weatherFor(to.icao);
|
||||||
const nextRequiredL = requiredFuelFor(
|
const nextRequiredL = requiredFuelFor(
|
||||||
type.burnPerKm * windBurnFactor(wNext.windKt, wNext.windDirDeg, initialBearingDeg(to.lat, to.lon, next.lat, next.lon)),
|
type.burnPerKm * windBurnFactor(wNext.windKt, wNext.windDirDeg, initialBearingDeg(to.lat, to.lon, next.lat, next.lon)) * conditionBurnMultiplier(newHealth),
|
||||||
type.emptyWeightKg,
|
type.emptyWeightKg,
|
||||||
type.maxFuel,
|
type.maxFuel,
|
||||||
haversineKm(to.lat, to.lon, next.lat, next.lon),
|
haversineKm(to.lat, to.lon, next.lat, next.lon),
|
||||||
@@ -214,6 +245,20 @@ export async function deliverPackages(inst: GameDb, clockMs: number): Promise<nu
|
|||||||
if (nextRequiredL <= landedFuel) {
|
if (nextRequiredL <= landedFuel) {
|
||||||
queue.shift();
|
queue.shift();
|
||||||
chainedTo = nextDest;
|
chainedTo = nextDest;
|
||||||
|
} else {
|
||||||
|
// ISS-082: auto top-up — same target/price terms as flyPlane's dispatch refuel.
|
||||||
|
const target = Math.min(type.maxFuel, Math.max(landedFuel, nextRequiredL * 1.5));
|
||||||
|
const liters = Math.max(0, target - landedFuel);
|
||||||
|
// Fresh account read (same pattern as the delivery awards above) so a top-up in this tick sees current cash.
|
||||||
|
const fresh = (await inst.db.select().from(schema.account))[0];
|
||||||
|
if (!fresh) throw new Error('account row missing');
|
||||||
|
const cost = Math.round(liters * FUEL_PRICE_PER_L * (1 - repRate(fresh.reputation, FUEL_DISCOUNT_PER_REP, MAX_FUEL_DISCOUNT)) * 100) / 100;
|
||||||
|
if (cost === 0 || fresh.cash >= cost) {
|
||||||
|
queue.shift();
|
||||||
|
chainedTo = nextDest;
|
||||||
|
topUpFuel = target;
|
||||||
|
if (cost > 0) await inst.db.update(schema.account).set({ cash: Math.round((fresh.cash - cost) * 100) / 100 });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -225,7 +270,8 @@ export async function deliverPackages(inst: GameDb, clockMs: number): Promise<nu
|
|||||||
locationIcao: to.icao,
|
locationIcao: to.icao,
|
||||||
lat: to.lat,
|
lat: to.lat,
|
||||||
lon: to.lon,
|
lon: to.lon,
|
||||||
fuel: landedFuel,
|
fuel: topUpFuel ?? landedFuel, // ISS-082: the post-top-up level when a top-up funded the chain
|
||||||
|
health: newHealth, // v0.39.0 (ISS-069) — this leg's wear persists into the chained flight
|
||||||
destIcao: chainedTo,
|
destIcao: chainedTo,
|
||||||
departureSimTime: clockMs, // the arrival instant — position is exactly `to`
|
departureSimTime: clockMs, // the arrival instant — position is exactly `to`
|
||||||
queue: JSON.stringify(queue),
|
queue: JSON.stringify(queue),
|
||||||
@@ -236,6 +282,7 @@ export async function deliverPackages(inst: GameDb, clockMs: number): Promise<nu
|
|||||||
lat: to.lat,
|
lat: to.lat,
|
||||||
lon: to.lon,
|
lon: to.lon,
|
||||||
fuel: landedFuel,
|
fuel: landedFuel,
|
||||||
|
health: newHealth, // v0.39.0 (ISS-069) — this leg's wear persists on the grounded plane
|
||||||
departureSimTime: null,
|
departureSimTime: null,
|
||||||
destIcao: null,
|
destIcao: null,
|
||||||
queue: JSON.stringify(queue),
|
queue: JSON.stringify(queue),
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "flight-ops",
|
"name": "flight-ops",
|
||||||
"version": "0.38.0",
|
"version": "0.42.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev -p 3000",
|
"dev": "next dev -p 3000",
|
||||||
|
|||||||
Reference in New Issue
Block a user