feat: v0.12.0 — contracts → packages: load/fly/abandon gameplay (ATR 72-600 capacity 6, manual flight to any airport, time-scaled abandon penalty 15–60%), one-time DB migration preserving wallet/clock; new endpoints /api/packages/:id/load|abandon + /api/planes/:planeId/fly
This commit is contained in:
+115
-6
@@ -42,6 +42,46 @@ CREATE TABLE sim_state (
|
||||
);
|
||||
`;
|
||||
|
||||
// The v0.11.0 DDL — the last schema before the packages pivot; used to build a
|
||||
// "pre-v0.12.0" DB file for the migration test (has departure_sim_time +
|
||||
// contract_id, has contracts, no packages/dest_icao).
|
||||
const PRE_V12_DDL = `
|
||||
CREATE TABLE planes (
|
||||
id TEXT PRIMARY KEY NOT NULL,
|
||||
model TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
fuel REAL NOT NULL,
|
||||
max_fuel REAL NOT NULL,
|
||||
location_icao TEXT NOT NULL,
|
||||
contract_id TEXT,
|
||||
lat REAL NOT NULL,
|
||||
lon REAL NOT NULL,
|
||||
departure_sim_time INTEGER
|
||||
);
|
||||
CREATE TABLE contracts (
|
||||
id TEXT PRIMARY KEY NOT NULL,
|
||||
origin_icao TEXT NOT NULL,
|
||||
dest_icao TEXT NOT NULL,
|
||||
reward REAL NOT NULL,
|
||||
cargo_type TEXT NOT NULL,
|
||||
cargo_count INTEGER NOT NULL,
|
||||
deadline_sim_time INTEGER NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
plane_id TEXT,
|
||||
created_sim_time INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE account (
|
||||
cash REAL NOT NULL,
|
||||
reputation REAL NOT NULL
|
||||
);
|
||||
CREATE TABLE sim_state (
|
||||
clock_ms INTEGER NOT NULL,
|
||||
time_scale REAL NOT NULL,
|
||||
paused INTEGER NOT NULL,
|
||||
last_real_tick_ms INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
`;
|
||||
|
||||
let dir: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
@@ -64,9 +104,9 @@ describe('openGameDb', () => {
|
||||
expect(planes[0].locationIcao).toBe('EDDF'); // Frankfurt hub from the CSV
|
||||
expect(planes[0].fuel).toBe(planes[0].maxFuel);
|
||||
|
||||
const contracts = await inst.db.select().from(schema.contracts);
|
||||
expect(contracts.length).toBeGreaterThanOrEqual(8);
|
||||
expect(contracts.every((c) => c.status === 'open')).toBe(true);
|
||||
const packages = await inst.db.select().from(schema.packages);
|
||||
expect(packages.length).toBeGreaterThanOrEqual(8);
|
||||
expect(packages.every((p) => p.status === 'open')).toBe(true);
|
||||
|
||||
const account = (await inst.db.select().from(schema.account))[0];
|
||||
expect(account?.cash).toBeGreaterThan(0);
|
||||
@@ -82,13 +122,13 @@ describe('openGameDb', () => {
|
||||
it('does not re-seed an existing DB — state survives reopen', async () => {
|
||||
const file = path.join(dir, 'reopen.db');
|
||||
const first = await openGameDb(file);
|
||||
const contracts1 = (await first.db.select().from(schema.contracts)).map((c) => c.id).sort();
|
||||
const packages1 = (await first.db.select().from(schema.packages)).map((p) => p.id).sort();
|
||||
const account1 = (await first.db.select().from(schema.account))[0];
|
||||
|
||||
// Simulate a process restart: brand-new instance over the same file.
|
||||
const second = await openGameDb(file);
|
||||
const contracts2 = (await second.db.select().from(schema.contracts)).map((c) => c.id).sort();
|
||||
expect(contracts2).toEqual(contracts1);
|
||||
const packages2 = (await second.db.select().from(schema.packages)).map((p) => p.id).sort();
|
||||
expect(packages2).toEqual(packages1);
|
||||
expect((await second.db.select().from(schema.account))[0]).toEqual(account1);
|
||||
});
|
||||
|
||||
@@ -128,4 +168,73 @@ describe('openGameDb', () => {
|
||||
// tick-on-read resumes cleanly instead of taking one clamped catch-up jump.
|
||||
expect(sim?.lastRealTickMs).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('migrates a pre-v0.12.0 database: wipes contracts, grounds planes, preserves account + clock', async () => {
|
||||
// Build a v0.11.0 file with an IN-FLIGHT plane (old dispatch state) and live contracts.
|
||||
const SQL = await initSqlJs();
|
||||
const raw = new SQL.Database();
|
||||
raw.exec(PRE_V12_DDL);
|
||||
raw.exec(
|
||||
`INSERT INTO planes VALUES ('plane-starter', 'atr72', 'flying', 4000, 6300, 'EDDF', 'c-1', 50.03, 8.57, 1789000000000)`,
|
||||
);
|
||||
raw.exec(
|
||||
`INSERT INTO contracts VALUES ('c-1', 'EDDF', 'LEMD', 5000, 'Mail', 4, 1789100000000, 'accepted', 'plane-starter', 1788900000000)`,
|
||||
);
|
||||
raw.exec(`INSERT INTO account VALUES (54020.34, 62.57)`);
|
||||
raw.exec('INSERT INTO sim_state VALUES (1789706016605, 1, 0, 1789718713288)');
|
||||
const file = path.join(dir, 'pre-v12.db');
|
||||
await fs.writeFile(file, Buffer.from(raw.export()));
|
||||
|
||||
const inst = await openGameDb(file);
|
||||
|
||||
// Wallet + sim clock survive byte-identical…
|
||||
expect((await inst.db.select().from(schema.account))[0]).toEqual({ cash: 54020.34, reputation: 62.57 });
|
||||
expect((await inst.db.select().from(schema.simState))[0]?.clockMs).toBe(1_789_706_016_605);
|
||||
|
||||
// …the in-flight plane is reset to GROUNDED at its locationIcao (it "lands" back where it took off)…
|
||||
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||
expect(plane.status).toBe('available');
|
||||
expect(plane.locationIcao).toBe('EDDF'); // unchanged — grounded AT the origin
|
||||
expect(plane.departureSimTime ?? null).toBeNull();
|
||||
expect(plane.destIcao ?? null).toBeNull();
|
||||
|
||||
// …old contract data is wiped and the packages table exists (empty until spawn reseeds)…
|
||||
let contractsGone = false;
|
||||
try {
|
||||
inst.raw.exec('SELECT COUNT(*) FROM contracts');
|
||||
} catch {
|
||||
contractsGone = true;
|
||||
}
|
||||
expect(contractsGone).toBe(true);
|
||||
const packages = await inst.db.select().from(schema.packages);
|
||||
expect(packages).toHaveLength(0);
|
||||
|
||||
// …and the orphaned contract_id column is dropped from planes.
|
||||
const cols = new Set(inst.raw.exec('PRAGMA table_info(planes)')[0].values.map((r) => String(r[1])));
|
||||
expect(cols.has('contract_id')).toBe(false);
|
||||
expect(cols.has('dest_icao')).toBe(true);
|
||||
});
|
||||
|
||||
it('does not re-run the v0.12 plane reset on later opens (migration is one-shot)', async () => {
|
||||
const file = path.join(dir, 'pre-v12-reopen.db');
|
||||
const SQL = await initSqlJs();
|
||||
const raw = new SQL.Database();
|
||||
raw.exec(PRE_V12_DDL);
|
||||
raw.exec(
|
||||
`INSERT INTO planes VALUES ('plane-starter', 'atr72', 'available', 6300, 6300, 'EDDF', NULL, 50.03, 8.57, NULL)`,
|
||||
);
|
||||
raw.exec(`INSERT INTO account VALUES (1000, 1)`);
|
||||
raw.exec('INSERT INTO sim_state VALUES (1789000000000, 1, 0, 1789000000000)');
|
||||
await fs.writeFile(file, Buffer.from(raw.export()));
|
||||
|
||||
const first = await openGameDb(file); // migration runs here
|
||||
// Simulate post-migration play: the plane flies again.
|
||||
await first.db.update(schema.planes).set({ status: 'flying', destIcao: 'LEMD', departureSimTime: 1789000001000 });
|
||||
await persist(first);
|
||||
|
||||
const second = await openGameDb(file); // must NOT ground the plane again
|
||||
const plane = (await second.db.select().from(schema.planes))[0];
|
||||
expect(plane.status).toBe('flying');
|
||||
expect(plane.destIcao).toBe('LEMD');
|
||||
});
|
||||
});
|
||||
|
||||
+46
-6
@@ -27,12 +27,12 @@ CREATE TABLE IF NOT EXISTS planes (
|
||||
fuel REAL NOT NULL,
|
||||
max_fuel REAL NOT NULL,
|
||||
location_icao TEXT NOT NULL,
|
||||
contract_id TEXT,
|
||||
dest_icao TEXT,
|
||||
lat REAL NOT NULL,
|
||||
lon REAL NOT NULL,
|
||||
departure_sim_time INTEGER
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS contracts (
|
||||
CREATE TABLE IF NOT EXISTS packages (
|
||||
id TEXT PRIMARY KEY NOT NULL,
|
||||
origin_icao TEXT NOT NULL,
|
||||
dest_icao TEXT NOT NULL,
|
||||
@@ -59,7 +59,7 @@ CREATE TABLE IF NOT EXISTS sim_state (
|
||||
// v0.7.0: DBs created by earlier versions lack the new columns; CREATE TABLE IF
|
||||
// NOT EXISTS won't add them, so ALTER (guarded by PRAGMA table_info). Fresh DBs
|
||||
// already have everything from DDL above and this is a no-op for them.
|
||||
function migrate(raw: RawSqlJsDatabase): void {
|
||||
function migrateColumns(raw: RawSqlJsDatabase): void {
|
||||
const cols = (table: string): Set<string> =>
|
||||
new Set(raw.exec(`PRAGMA table_info(${table})`)[0].values.map((r) => String(r[1])));
|
||||
if (!cols('sim_state').has('last_real_tick_ms')) {
|
||||
@@ -68,6 +68,37 @@ function migrate(raw: RawSqlJsDatabase): void {
|
||||
if (!cols('planes').has('departure_sim_time')) {
|
||||
raw.exec('ALTER TABLE planes ADD COLUMN departure_sim_time INTEGER');
|
||||
}
|
||||
// v0.12.0: the flight destination column (set by fly, cleared on arrival).
|
||||
if (!cols('planes').has('dest_icao')) {
|
||||
raw.exec('ALTER TABLE planes ADD COLUMN dest_icao TEXT');
|
||||
}
|
||||
}
|
||||
|
||||
// v0.12.0 one-time migration: contracts world → packages world. Detected by the
|
||||
// presence of the old `contracts` table (fresh and already-migrated DBs never
|
||||
// have it, so this runs exactly once per file). Preserves account/sim_state rows
|
||||
// and every plane row; planes are reset to GROUNDED at their locationIcao with
|
||||
// departure_sim_time/dest_icao cleared — an in-flight plane from the old state
|
||||
// simply lands back where it took off. Old contract data is wiped (the packages
|
||||
// table starts empty and the engine's spawn rules reseed the market on the next
|
||||
// tick). The orphaned pre-v0.12.0 `contract_id` column is dropped too (SQLite
|
||||
// ≥3.35 DROP COLUMN; guarded so a failure can never block startup).
|
||||
function migrateContractsToPackages(raw: RawSqlJsDatabase): void {
|
||||
const cols = new Set(
|
||||
raw.exec('PRAGMA table_info(planes)')[0].values.map((r) => String(r[1])),
|
||||
);
|
||||
raw.exec(
|
||||
`UPDATE planes SET status = 'available', departure_sim_time = NULL, dest_icao = NULL` +
|
||||
(cols.has('contract_id') ? ', contract_id = NULL' : ''),
|
||||
);
|
||||
if (cols.has('contract_id')) {
|
||||
try {
|
||||
raw.exec('ALTER TABLE planes DROP COLUMN contract_id');
|
||||
} catch {
|
||||
// Leaving the orphaned column is harmless — nothing references it anymore.
|
||||
}
|
||||
}
|
||||
raw.exec('DROP TABLE contracts');
|
||||
}
|
||||
|
||||
// FLIGHT_DB_PATH override exists so unit tests can point at a temp file instead
|
||||
@@ -85,8 +116,17 @@ async function open(file: string): Promise<GameDb> {
|
||||
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;
|
||||
}
|
||||
const raw = bytes ? new SQL.Database(new Uint8Array(bytes)) : new SQL.Database();
|
||||
raw.exec(DDL);
|
||||
migrate(raw);
|
||||
raw.exec(DDL); // no-op for tables that already exist in an older file
|
||||
migrateColumns(raw);
|
||||
|
||||
// v0.12.0: run BEFORE the seed check — a pre-v0.12.0 file has account rows, so
|
||||
// without this it would keep the dead contracts table forever.
|
||||
const tables = new Set(
|
||||
raw.exec("SELECT name FROM sqlite_master WHERE type='table'")[0].values.map((r) => String(r[0])),
|
||||
);
|
||||
if (tables.has('contracts')) {
|
||||
migrateContractsToPackages(raw);
|
||||
}
|
||||
|
||||
const instance: GameDb = { db: drizzle(raw, { schema }), raw, file };
|
||||
|
||||
@@ -120,7 +160,7 @@ async function seedEmpty(instance: GameDb): Promise<void> {
|
||||
const data = buildSeed({ airports, rng, nowMs: Date.now() });
|
||||
|
||||
await instance.db.insert(schema.planes).values(data.plane);
|
||||
await instance.db.insert(schema.contracts).values(data.contracts);
|
||||
await instance.db.insert(schema.packages).values(data.packages);
|
||||
await instance.db.insert(schema.account).values(data.account);
|
||||
await instance.db.insert(schema.simState).values(data.simState);
|
||||
await persist(instance);
|
||||
|
||||
+12
-6
@@ -11,7 +11,9 @@ export const planes = sqliteTable('planes', {
|
||||
fuel: real('fuel').notNull(),
|
||||
maxFuel: real('max_fuel').notNull(),
|
||||
locationIcao: text('location_icao').notNull(),
|
||||
contractId: text('contract_id'),
|
||||
// Current flight destination (v0.12.0) — set by fly, cleared on arrival. The
|
||||
// plane's origin is always its locationIcao while flying.
|
||||
destIcao: text('dest_icao'),
|
||||
lat: real('lat').notNull(),
|
||||
lon: real('lon').notNull(),
|
||||
// Sim-clock departure time of the current flight (null when available). While
|
||||
@@ -20,7 +22,11 @@ export const planes = sqliteTable('planes', {
|
||||
departureSimTime: integer('departure_sim_time'),
|
||||
});
|
||||
|
||||
export const contracts = sqliteTable('contracts', {
|
||||
// Cargo packages (v0.12.0) replace the old contracts table end-to-end: a package
|
||||
// is one cargo unit origin → dest with a reward and deadline. 'loaded' = bound to
|
||||
// a plane's slot; it stays bound ('expired') or pays out ('delivered') when the
|
||||
// plane arrives at its destination airport.
|
||||
export const packages = sqliteTable('packages', {
|
||||
id: text('id').primaryKey().notNull(),
|
||||
originIcao: text('origin_icao').notNull(),
|
||||
destIcao: text('dest_icao').notNull(),
|
||||
@@ -28,9 +34,9 @@ export const contracts = sqliteTable('contracts', {
|
||||
cargoType: text('cargo_type').notNull(),
|
||||
cargoCount: integer('cargo_count').notNull(),
|
||||
deadlineSimTime: integer('deadline_sim_time').notNull(),
|
||||
// 'expired' = an open contract whose deadline passed (v0.7.0). Accepted/
|
||||
// in-flight contracts never expire — they complete.
|
||||
status: text('status', { enum: ['open', 'accepted', 'completed', 'expired'] }).notNull(),
|
||||
// 'expired' = an open OR loaded package whose deadline passed on a tick. Loaded
|
||||
// expired packages keep occupying their slot, deliver no reward, and abandon free.
|
||||
status: text('status', { enum: ['open', 'loaded', 'delivered', 'expired', 'abandoned'] }).notNull(),
|
||||
planeId: text('plane_id'),
|
||||
createdSimTime: integer('created_sim_time').notNull(),
|
||||
});
|
||||
@@ -50,6 +56,6 @@ export const simState = sqliteTable('sim_state', {
|
||||
});
|
||||
|
||||
export type PlaneRow = typeof planes.$inferSelect;
|
||||
export type ContractRow = typeof contracts.$inferSelect;
|
||||
export type PackageRow = typeof packages.$inferSelect;
|
||||
export type AccountRow = typeof account.$inferSelect;
|
||||
export type SimStateRow = typeof simState.$inferSelect;
|
||||
|
||||
+194
-69
@@ -9,10 +9,11 @@ import { loadAirportsGeoJson } from '@/lib/airports';
|
||||
import { FUEL_PRICE_PER_L, PLANE_TYPES, SELL_FRACTION } from './catalog';
|
||||
import { HUB_ICAO } from './seed';
|
||||
import {
|
||||
acceptContract,
|
||||
abandonPackage,
|
||||
buyPlane,
|
||||
dispatchPlane,
|
||||
flyPlane,
|
||||
GameActionError,
|
||||
loadPackage,
|
||||
refuelPlane,
|
||||
sellPlane,
|
||||
} from './actions';
|
||||
@@ -54,54 +55,107 @@ function expectActionError(promise: Promise<unknown>, status: number, messagePar
|
||||
);
|
||||
}
|
||||
|
||||
// Insert an accepted contract EDDF → LEMD bound to nothing, for dispatch tests.
|
||||
async function insertAcceptedContract(inst: GameDb, id = 'c-acc'): Promise<void> {
|
||||
await inst.db.insert(schema.contracts).values({
|
||||
// Insert a known OPEN package EDDF → LEMD for load tests.
|
||||
async function insertOpenPackage(inst: GameDb, id = 'p-open', over: Partial<schema.PackageRow> = {}): Promise<void> {
|
||||
await inst.db.insert(schema.packages).values({
|
||||
id,
|
||||
originIcao: HUB_ICAO,
|
||||
destIcao: 'LEMD',
|
||||
reward: 5_000,
|
||||
cargoType: 'Passengers',
|
||||
cargoCount: 60,
|
||||
reward: 1_000,
|
||||
cargoType: 'Mail',
|
||||
cargoCount: 4,
|
||||
deadlineSimTime: T0 + 24 * 3_600_000,
|
||||
status: 'accepted',
|
||||
status: 'open',
|
||||
planeId: null,
|
||||
createdSimTime: T0,
|
||||
...over,
|
||||
});
|
||||
}
|
||||
|
||||
describe('acceptContract', () => {
|
||||
it('flips an open contract to accepted and persists it', async () => {
|
||||
const inst = await freshDb('acc-open.db');
|
||||
await acceptContract(inst, 'contract-1'); // seeded ids are contract-N
|
||||
describe('loadPackage', () => {
|
||||
it('binds an open package to a grounded plane at its origin', async () => {
|
||||
const inst = await freshDb('load-ok.db');
|
||||
await insertOpenPackage(inst);
|
||||
|
||||
const row = (await inst.db.select().from(schema.contracts).where(eq(schema.contracts.id, 'contract-1')))[0];
|
||||
expect(row.status).toBe('accepted');
|
||||
await loadPackage(inst, 'p-open', 'plane-starter'); // seeded starter is grounded at EDDF
|
||||
|
||||
const row = (await inst.db.select().from(schema.packages).where(eq(schema.packages.id, 'p-open')))[0];
|
||||
expect(row.status).toBe('loaded');
|
||||
expect(row.planeId).toBe('plane-starter');
|
||||
});
|
||||
|
||||
it.each(['accepted', 'completed', 'expired'] as const)('rejects a %s contract with 409', async (status) => {
|
||||
const inst = await freshDb(`acc-${status}.db`);
|
||||
await inst.db.update(schema.contracts).set({ status }).where(eq(schema.contracts.id, 'contract-1'));
|
||||
it.each(['loaded', 'delivered', 'expired', 'abandoned'] as const)(
|
||||
'rejects a %s package with 409 (must be open)',
|
||||
async (status) => {
|
||||
const inst = await freshDb(`load-${status}.db`);
|
||||
await insertOpenPackage(inst, 'p-x', { status });
|
||||
|
||||
await expectActionError(acceptContract(inst, 'contract-1'), 409, new RegExp(status));
|
||||
await expectActionError(loadPackage(inst, 'p-x', 'plane-starter'), 409, new RegExp(status));
|
||||
},
|
||||
);
|
||||
|
||||
it('rejects an unknown package id with 404', async () => {
|
||||
const inst = await freshDb('load-punknown.db');
|
||||
await expectActionError(loadPackage(inst, 'nope', 'plane-starter'), 404);
|
||||
});
|
||||
|
||||
it('rejects an unknown id with 404', async () => {
|
||||
const inst = await freshDb('acc-unknown.db');
|
||||
await expectActionError(acceptContract(inst, 'nope'), 404);
|
||||
it('rejects an unknown plane id with 404', async () => {
|
||||
const inst = await freshDb('load-ghost.db');
|
||||
await insertOpenPackage(inst);
|
||||
await expectActionError(loadPackage(inst, 'p-open', 'ghost'), 404);
|
||||
});
|
||||
|
||||
it('rejects a flying plane with 409', async () => {
|
||||
const inst = await freshDb('load-flying.db');
|
||||
await insertOpenPackage(inst);
|
||||
await inst.db.update(schema.planes)
|
||||
.set({ status: 'flying', departureSimTime: T0, destIcao: 'LEMD' })
|
||||
.where(eq(schema.planes.id, 'plane-starter'));
|
||||
|
||||
await expectActionError(loadPackage(inst, 'p-open', 'plane-starter'), 409);
|
||||
});
|
||||
|
||||
it('rejects a plane that is not at the origin with 409', async () => {
|
||||
const inst = await freshDb('load-notatorigin.db');
|
||||
await insertOpenPackage(inst); // originates at EDDF
|
||||
await inst.db.update(schema.planes).set({ locationIcao: 'LEMD' }).where(eq(schema.planes.id, 'plane-starter'));
|
||||
|
||||
await expectActionError(loadPackage(inst, 'p-open', 'plane-starter'), 409, /at LEMD/);
|
||||
});
|
||||
|
||||
it('rejects loading when the plane has no free slot (capacity from catalog)', async () => {
|
||||
const inst = await freshDb('load-full.db');
|
||||
await insertOpenPackage(inst, 'p-new');
|
||||
// Fill all atr72 slots with loaded cargo…
|
||||
for (let i = 0; i < PLANE_TYPES.atr72.capacity; i++) {
|
||||
await insertOpenPackage(inst, `p-fill-${i}`, { status: 'loaded', planeId: 'plane-starter' });
|
||||
}
|
||||
|
||||
await expectActionError(loadPackage(inst, 'p-new', 'plane-starter'), 409, /no free slots/i);
|
||||
});
|
||||
|
||||
it('counts expired packages as occupying their slot too', async () => {
|
||||
const inst = await freshDb('load-expiredslot.db');
|
||||
await insertOpenPackage(inst, 'p-new');
|
||||
// capacity − 1 loaded + 1 expired = full.
|
||||
for (let i = 0; i < PLANE_TYPES.atr72.capacity - 1; i++) {
|
||||
await insertOpenPackage(inst, `p-fill-${i}`, { status: 'loaded', planeId: 'plane-starter' });
|
||||
}
|
||||
await insertOpenPackage(inst, 'p-expired-slot', { status: 'expired', planeId: 'plane-starter' });
|
||||
|
||||
await expectActionError(loadPackage(inst, 'p-new', 'plane-starter'), 409, /no free slots/i);
|
||||
});
|
||||
});
|
||||
|
||||
describe('dispatchPlane', () => {
|
||||
it('binds the plane: flying + departure at current clock + origin coords, contract bound to plane', async () => {
|
||||
const inst = await freshDb('disp-ok.db');
|
||||
await insertAcceptedContract(inst);
|
||||
describe('flyPlane', () => {
|
||||
it('sets flying + departure at current clock + dest_icao + origin coords', async () => {
|
||||
const inst = await freshDb('fly-ok.db');
|
||||
|
||||
await dispatchPlane(inst, 'plane-starter', 'c-acc');
|
||||
await flyPlane(inst, 'plane-starter', 'LEMD');
|
||||
|
||||
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||
expect(plane.status).toBe('flying');
|
||||
expect(plane.contractId).toBe('c-acc');
|
||||
expect(plane.destIcao).toBe('LEMD');
|
||||
expect(plane.departureSimTime).toBe(T0); // seeded clock, no tick in direct calls
|
||||
const fc = await loadAirportsGeoJson();
|
||||
const origin = fc.features.find((f) => f.properties.icao === HUB_ICAO)!.properties;
|
||||
@@ -109,58 +163,129 @@ describe('dispatchPlane', () => {
|
||||
expect(plane.lon).toBe(origin.lon);
|
||||
// Fuel is frozen at the departure value while flying (live fuel is analytic).
|
||||
expect(plane.fuel).toBe(PLANE_TYPES.atr72.maxFuel);
|
||||
|
||||
const contract = (await inst.db.select().from(schema.contracts).where(eq(schema.contracts.id, 'c-acc')))[0];
|
||||
expect(contract.planeId).toBe('plane-starter');
|
||||
});
|
||||
|
||||
it.each(['open', 'completed', 'expired'] as const)('rejects a %s contract with 409 (must be accepted)', async (status) => {
|
||||
const inst = await freshDb(`disp-c${status}.db`);
|
||||
await inst.db.insert(schema.contracts).values({
|
||||
id: 'c-x', originIcao: HUB_ICAO, destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1,
|
||||
deadlineSimTime: T0 + 3_600_000, status, planeId: null, createdSimTime: T0,
|
||||
});
|
||||
|
||||
await expectActionError(dispatchPlane(inst, 'plane-starter', 'c-x'), 409, new RegExp(status));
|
||||
});
|
||||
|
||||
it('rejects an unknown contract id with 404', async () => {
|
||||
const inst = await freshDb('disp-cunknown.db');
|
||||
await expectActionError(dispatchPlane(inst, 'plane-starter', 'nope'), 404);
|
||||
});
|
||||
|
||||
it('rejects an unknown plane id with 404', async () => {
|
||||
const inst = await freshDb('disp-punknown.db');
|
||||
await insertAcceptedContract(inst);
|
||||
await expectActionError(dispatchPlane(inst, 'ghost', 'c-acc'), 404);
|
||||
});
|
||||
|
||||
it('rejects a flying plane with 409', async () => {
|
||||
const inst = await freshDb('disp-flying.db');
|
||||
await insertAcceptedContract(inst);
|
||||
const inst = await freshDb('fly-flying.db');
|
||||
await inst.db.update(schema.planes)
|
||||
.set({ status: 'flying', departureSimTime: T0, contractId: 'c-other' })
|
||||
.set({ status: 'flying', departureSimTime: T0, destIcao: 'LEMD' })
|
||||
.where(eq(schema.planes.id, 'plane-starter'));
|
||||
|
||||
await expectActionError(dispatchPlane(inst, 'plane-starter', 'c-acc'), 409);
|
||||
await expectActionError(flyPlane(inst, 'plane-starter', 'EDDM'), 409);
|
||||
});
|
||||
|
||||
it('rejects a plane that is not at the origin with 409', async () => {
|
||||
const inst = await freshDb('disp-notatorigin.db');
|
||||
await insertAcceptedContract(inst); // originates at EDDF
|
||||
await inst.db.update(schema.planes)
|
||||
.set({ locationIcao: 'LEMD' })
|
||||
.where(eq(schema.planes.id, 'plane-starter'));
|
||||
it('rejects an unknown plane id with 404', async () => {
|
||||
const inst = await freshDb('fly-ghost.db');
|
||||
await expectActionError(flyPlane(inst, 'ghost', 'LEMD'), 404);
|
||||
});
|
||||
|
||||
await expectActionError(dispatchPlane(inst, 'plane-starter', 'c-acc'), 409, /not at|at LEMD/);
|
||||
it('rejects an ICAO not in the airport dataset with 400', async () => {
|
||||
const inst = await freshDb('fly-unknownicao.db');
|
||||
await expectActionError(flyPlane(inst, 'plane-starter', 'ZZZZ'), 400, /unknown airport/);
|
||||
});
|
||||
|
||||
it('rejects a leg the plane cannot fuel with 409 (burn > fuel)', async () => {
|
||||
const inst = await freshDb('disp-nofuel.db');
|
||||
await insertAcceptedContract(inst); // EDDF → LEMD ≈ 1950 km × 1.75 L/km ≈ 3400 L
|
||||
const inst = await freshDb('fly-nofuel.db'); // EDDF → LEMD ≈ 1950 km × 1.75 L/km ≈ 3400 L
|
||||
await inst.db.update(schema.planes).set({ fuel: 1 }).where(eq(schema.planes.id, 'plane-starter'));
|
||||
|
||||
await expectActionError(dispatchPlane(inst, 'plane-starter', 'c-acc'), 409, /insufficient fuel/i);
|
||||
await expectActionError(flyPlane(inst, 'plane-starter', 'LEMD'), 409, /insufficient fuel/i);
|
||||
});
|
||||
});
|
||||
|
||||
describe('abandonPackage', () => {
|
||||
// A loaded package created at T0 with a 10h window; the seeded sim clock is T0.
|
||||
const REWARD = 1_000;
|
||||
const WINDOW_MS = 10 * 3_600_000;
|
||||
|
||||
async function setupLoaded(name: string, status: 'loaded' | 'expired' = 'loaded') {
|
||||
const inst = await freshDb(name);
|
||||
// Always insert OPEN and load it through the real action…
|
||||
await insertOpenPackage(inst, 'p-ab', { reward: REWARD, createdSimTime: T0, deadlineSimTime: T0 + WINDOW_MS });
|
||||
await loadPackage(inst, 'p-ab', 'plane-starter');
|
||||
// …then flip to expired in place (what the tick would do once the deadline passes).
|
||||
if (status === 'expired') {
|
||||
await inst.db.update(schema.packages).set({ status: 'expired' }).where(eq(schema.packages.id, 'p-ab'));
|
||||
}
|
||||
return inst;
|
||||
}
|
||||
|
||||
it('charges exactly 15% of the payout right after creation (clock at createdSimTime)', async () => {
|
||||
const inst = await setupLoaded('ab-start.db');
|
||||
const cashBefore = (await inst.db.select().from(schema.account))[0].cash;
|
||||
|
||||
const { penalty } = await abandonPackage(inst, 'p-ab');
|
||||
|
||||
expect(penalty).toBe(Math.round(REWARD * 0.15 * 100) / 100);
|
||||
const row = (await inst.db.select().from(schema.packages).where(eq(schema.packages.id, 'p-ab')))[0];
|
||||
expect(row.status).toBe('abandoned');
|
||||
expect(row.planeId).toBeNull(); // slot freed
|
||||
const account = (await inst.db.select().from(schema.account))[0];
|
||||
expect(account.cash).toBeCloseTo(cashBefore - penalty, 6);
|
||||
});
|
||||
|
||||
it('scales to exactly 37.5% at the midpoint of the window', async () => {
|
||||
const inst = await setupLoaded('ab-mid.db');
|
||||
await inst.db.update(schema.simState).set({ clockMs: T0 + WINDOW_MS / 2 }); // runAction ticks first in prod
|
||||
|
||||
const { penalty } = await abandonPackage(inst, 'p-ab');
|
||||
|
||||
expect(penalty).toBe(Math.round(REWARD * (0.15 + 0.45 * 0.5) * 100) / 100);
|
||||
});
|
||||
|
||||
it('caps at exactly 60% at and past the deadline', async () => {
|
||||
for (const [name, clock] of [
|
||||
['ab-deadline.db', T0 + WINDOW_MS],
|
||||
['ab-pastdeadline.db', T0 + WINDOW_MS * 2], // clamped — a not-yet-ticked loaded package past its deadline
|
||||
] as const) {
|
||||
const inst = await setupLoaded(name);
|
||||
await inst.db.update(schema.simState).set({ clockMs: clock });
|
||||
|
||||
const { penalty } = await abandonPackage(inst, 'p-ab');
|
||||
expect(penalty).toBe(Math.round(REWARD * 0.6 * 100) / 100);
|
||||
}
|
||||
});
|
||||
|
||||
it('is free for an already-expired package', async () => {
|
||||
const inst = await setupLoaded('ab-expired.db', 'expired');
|
||||
const cashBefore = (await inst.db.select().from(schema.account))[0].cash;
|
||||
|
||||
const { penalty } = await abandonPackage(inst, 'p-ab');
|
||||
|
||||
expect(penalty).toBe(0);
|
||||
expect((await inst.db.select().from(schema.account))[0].cash).toBe(cashBefore);
|
||||
const row = (await inst.db.select().from(schema.packages).where(eq(schema.packages.id, 'p-ab')))[0];
|
||||
expect(row.status).toBe('abandoned');
|
||||
});
|
||||
|
||||
it('floors cash at €0 — no debt', async () => {
|
||||
const inst = await setupLoaded('ab-floor.db');
|
||||
await inst.db.update(schema.account).set({ cash: 10 }); // penalty is 150 > 10
|
||||
|
||||
const { penalty } = await abandonPackage(inst, 'p-ab');
|
||||
|
||||
expect(penalty).toBe(150);
|
||||
expect((await inst.db.select().from(schema.account))[0].cash).toBe(0);
|
||||
});
|
||||
|
||||
it('rejects abandoning while the plane is in flight with 409', async () => {
|
||||
const inst = await setupLoaded('ab-flying.db');
|
||||
await inst.db.update(schema.planes)
|
||||
.set({ status: 'flying', departureSimTime: T0, destIcao: 'LEMD' })
|
||||
.where(eq(schema.planes.id, 'plane-starter'));
|
||||
|
||||
await expectActionError(abandonPackage(inst, 'p-ab'), 409, /in flight/i);
|
||||
});
|
||||
|
||||
it.each(['open', 'delivered', 'abandoned'] as const)('rejects a %s package with 409', async (status) => {
|
||||
const inst = await freshDb(`ab-${status}.db`);
|
||||
await insertOpenPackage(inst, 'p-x', { status });
|
||||
|
||||
await expectActionError(abandonPackage(inst, 'p-x'), 409, new RegExp(status));
|
||||
});
|
||||
|
||||
it('rejects an unknown id with 404', async () => {
|
||||
const inst = await freshDb('ab-unknown.db');
|
||||
await expectActionError(abandonPackage(inst, 'nope'), 404);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -206,7 +331,7 @@ describe('sellPlane', () => {
|
||||
// A second plane so the starter is not "the last remaining one".
|
||||
await inst.db.insert(schema.planes).values({
|
||||
id: 'plane-extra', model: 'atr72', status: 'available', fuel: 100, maxFuel: PLANE_TYPES.atr72.maxFuel,
|
||||
locationIcao: HUB_ICAO, contractId: null, lat: 50, lon: 8, departureSimTime: null,
|
||||
locationIcao: HUB_ICAO, destIcao: null, lat: 50, lon: 8, departureSimTime: null,
|
||||
});
|
||||
const cashBefore = (await inst.db.select().from(schema.account))[0].cash;
|
||||
|
||||
@@ -224,7 +349,7 @@ describe('sellPlane', () => {
|
||||
const inst = await freshDb('sell-flying.db');
|
||||
await inst.db.insert(schema.planes).values({
|
||||
id: 'plane-extra', model: 'atr72', status: 'flying', fuel: 100, maxFuel: PLANE_TYPES.atr72.maxFuel,
|
||||
locationIcao: HUB_ICAO, contractId: null, lat: 50, lon: 8, departureSimTime: T0,
|
||||
locationIcao: HUB_ICAO, destIcao: 'LEMD', lat: 50, lon: 8, departureSimTime: T0,
|
||||
});
|
||||
|
||||
await expectActionError(sellPlane(inst, 'plane-extra'), 409, /flying/);
|
||||
@@ -269,7 +394,7 @@ describe('refuelPlane', () => {
|
||||
it('rejects a flying plane with 409', async () => {
|
||||
const inst = await freshDb('refuel-flying.db');
|
||||
await inst.db.update(schema.planes)
|
||||
.set({ status: 'flying', departureSimTime: T0, contractId: 'c-x' })
|
||||
.set({ status: 'flying', departureSimTime: T0, destIcao: 'LEMD' })
|
||||
.where(eq(schema.planes.id, 'plane-starter'));
|
||||
|
||||
await expectActionError(refuelPlane(inst, 'plane-starter'), 409, /flying/);
|
||||
|
||||
+99
-45
@@ -1,5 +1,5 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { and, eq, inArray } from 'drizzle-orm';
|
||||
import * as schema from '@/lib/db/schema';
|
||||
import { persist, type GameDb } from '@/lib/db/client';
|
||||
import { loadAirportsGeoJson } from '@/lib/airports';
|
||||
@@ -7,17 +7,20 @@ import { haversineKm } from '@/lib/geo';
|
||||
import { runAction } from '@/lib/sim/engine';
|
||||
import { getStateSnapshot } from './state';
|
||||
import { FUEL_PRICE_PER_L, PLANE_TYPES, SELL_FRACTION } from './catalog';
|
||||
import { abandonPenalty } from './penalty';
|
||||
import { HUB_ICAO } from './seed';
|
||||
|
||||
// Player actions (v0.8.0) — the core loop, server-side: accept a contract,
|
||||
// dispatch a plane on it, buy/sell planes, refuel. Each function validates and
|
||||
// mutates ONE throwaway-safe GameDb instance (persisted at the end); routes wrap
|
||||
// them in engine.runAction() so tick + validate + mutate are atomic under the sim
|
||||
// lock. Validation failures throw GameActionError carrying the HTTP status:
|
||||
// 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
|
||||
// on arrival, abandon for a penalty while grounded; plus buy/sell planes and
|
||||
// refuel. Each function validates and mutates ONE throwaway-safe GameDb instance
|
||||
// (persisted at the end); routes wrap them in engine.runAction() so tick +
|
||||
// validate + mutate are atomic under the sim lock. Validation failures throw
|
||||
// GameActionError carrying the HTTP status:
|
||||
// 404 — unknown entity id
|
||||
// 409 — valid ids but the current state forbids the action (wrong contract/plane
|
||||
// status, plane not at origin, insufficient fuel/funds, last plane)
|
||||
// 400 — bad input that isn't an existence problem (unknown catalog model)
|
||||
// 409 — valid ids but the current state forbids the action (wrong package/plane
|
||||
// status, plane not at origin, no free slot, insufficient fuel/funds, last plane)
|
||||
// 400 — bad input that isn't an existence problem (unknown airport/model)
|
||||
|
||||
export class GameActionError extends Error {
|
||||
constructor(
|
||||
@@ -36,54 +39,72 @@ async function airportByIcao(icao: string): Promise<{ icao: string; lat: number;
|
||||
return { icao: f.properties.icao, lat: f.properties.lat, lon: f.properties.lon };
|
||||
}
|
||||
|
||||
// --- Accept (POST /api/contracts/:id/accept) ---
|
||||
// --- Load (POST /api/packages/:id/load {planeId}) ---
|
||||
|
||||
// open → accepted. Single-player, so no ownership tracking beyond the status flip;
|
||||
// an accepted contract is claimed by whoever dispatched it first (dispatch checks
|
||||
// 'accepted' and binds the plane).
|
||||
export async function acceptContract(inst: GameDb, contractId: string): Promise<void> {
|
||||
const rows = await inst.db.select().from(schema.contracts).where(eq(schema.contracts.id, contractId));
|
||||
const contract = rows[0];
|
||||
if (!contract) throw new GameActionError(404, `contract ${contractId} not found`);
|
||||
if (contract.status !== 'open') {
|
||||
throw new GameActionError(409, `contract is ${contract.status}, only open contracts can be accepted`);
|
||||
}
|
||||
await inst.db.update(schema.contracts).set({ status: 'accepted' }).where(eq(schema.contracts.id, contractId));
|
||||
await persist(inst);
|
||||
}
|
||||
|
||||
// --- Dispatch (POST /api/planes/:planeId/dispatch {contractId}) ---
|
||||
|
||||
// Bind an accepted contract to a grounded plane at its origin. The v0.7.0
|
||||
// finalize path then handles the flight: position/fuel are pure functions of the
|
||||
// clock from departureSimTime, and arrival awards cash + reputation automatically.
|
||||
export async function dispatchPlane(inst: GameDb, planeId: string, contractId: string): Promise<void> {
|
||||
const [planeRows, contractRows] = await Promise.all([
|
||||
// open → loaded, bound to the plane. The plane must be GROUNDED at the package's
|
||||
// origin with a free slot (slots = packages 'loaded' or 'expired' on it — expired
|
||||
// cargo keeps occupying its space until delivered/abandoned).
|
||||
export async function loadPackage(inst: GameDb, packageId: string, planeId: string): Promise<void> {
|
||||
const [pkgRows, planeRows] = await Promise.all([
|
||||
inst.db.select().from(schema.packages).where(eq(schema.packages.id, packageId)),
|
||||
inst.db.select().from(schema.planes).where(eq(schema.planes.id, planeId)),
|
||||
inst.db.select().from(schema.contracts).where(eq(schema.contracts.id, contractId)),
|
||||
]);
|
||||
const contract = contractRows[0];
|
||||
if (!contract) throw new GameActionError(404, `contract ${contractId} not found`);
|
||||
if (contract.status !== 'accepted') {
|
||||
throw new GameActionError(409, `contract is ${contract.status}, it must be accepted before dispatching`);
|
||||
const pkg = pkgRows[0];
|
||||
if (!pkg) throw new GameActionError(404, `package ${packageId} not found`);
|
||||
if (pkg.status !== 'open') {
|
||||
throw new GameActionError(409, `package is ${pkg.status}, only open packages can be loaded`);
|
||||
}
|
||||
const plane = planeRows[0];
|
||||
if (!plane) throw new GameActionError(404, `plane ${planeId} not found`);
|
||||
if (plane.status !== 'available') {
|
||||
throw new GameActionError(409, `plane is ${plane.status}, only available planes can be dispatched`);
|
||||
throw new GameActionError(409, `plane is ${plane.status}, only grounded planes can load cargo`);
|
||||
}
|
||||
if (plane.locationIcao !== contract.originIcao) {
|
||||
if (plane.locationIcao !== pkg.originIcao) {
|
||||
throw new GameActionError(
|
||||
409,
|
||||
`plane is at ${plane.locationIcao} but the contract originates at ${contract.originIcao}`,
|
||||
`plane is at ${plane.locationIcao} but the package originates at ${pkg.originIcao}`,
|
||||
);
|
||||
}
|
||||
|
||||
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(contract.originIcao);
|
||||
const dest = await airportByIcao(contract.destIcao);
|
||||
const distanceKm = haversineKm(origin.lat, origin.lon, dest.lat, dest.lon);
|
||||
const occupied = (
|
||||
await inst.db.select().from(schema.packages).where(
|
||||
and(inArray(schema.packages.status, ['loaded', 'expired']), eq(schema.packages.planeId, plane.id)),
|
||||
)
|
||||
).length;
|
||||
if (occupied >= type.capacity) {
|
||||
throw new GameActionError(409, `no free slots: the ${type.name} carries ${occupied}/${type.capacity} packages`);
|
||||
}
|
||||
|
||||
await inst.db.update(schema.packages)
|
||||
.set({ status: 'loaded', planeId })
|
||||
.where(eq(schema.packages.id, packageId));
|
||||
await persist(inst);
|
||||
}
|
||||
|
||||
// --- Fly (POST /api/planes/:id/fly {destIcao}) ---
|
||||
|
||||
// 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
|
||||
// delivers whatever is bound for that airport. Validation: plane 'available',
|
||||
// destination in the airport dataset, enough fuel for the leg.
|
||||
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 plane = planeRows[0];
|
||||
if (!plane) throw new GameActionError(404, `plane ${planeId} not found`);
|
||||
if (plane.status !== 'available') {
|
||||
throw new GameActionError(409, `plane is ${plane.status}, only grounded planes can fly`);
|
||||
}
|
||||
|
||||
const fc = await loadAirportsGeoJson();
|
||||
const destFeature = fc.features.find((f) => f.properties.icao === destIcao);
|
||||
if (!destFeature) throw new GameActionError(400, `unknown airport ${destIcao}`);
|
||||
const origin = await airportByIcao(plane.locationIcao);
|
||||
|
||||
const type = PLANE_TYPES[plane.model];
|
||||
if (!type) throw new Error(`unknown plane model ${plane.model}`); // → 500, cannot happen for seeded data
|
||||
const distanceKm = haversineKm(origin.lat, origin.lon, destFeature.properties.lat, destFeature.properties.lon);
|
||||
const burnL = type.burnPerKm * distanceKm;
|
||||
if (burnL > plane.fuel) {
|
||||
throw new GameActionError(409, `insufficient fuel: the leg needs ${Math.round(burnL)} L but the plane has ${Math.round(plane.fuel)} L`);
|
||||
@@ -96,16 +117,49 @@ export async function dispatchPlane(inst: GameDb, planeId: string, contractId: s
|
||||
await inst.db.update(schema.planes)
|
||||
.set({
|
||||
status: 'flying',
|
||||
contractId,
|
||||
destIcao,
|
||||
departureSimTime: sim.clockMs,
|
||||
lat: origin.lat,
|
||||
lon: origin.lon,
|
||||
})
|
||||
.where(eq(schema.planes.id, planeId));
|
||||
await inst.db.update(schema.contracts).set({ planeId }).where(eq(schema.contracts.id, contractId));
|
||||
await persist(inst);
|
||||
}
|
||||
|
||||
// --- Abandon (POST /api/packages/:id/abandon) ---
|
||||
|
||||
// Drop a package that is on a GROUNDED plane. Penalty = fraction of the payout
|
||||
// scaling with time pressure (15% at creation → 60% at the deadline, see
|
||||
// lib/game/penalty.ts); an already-expired package abandons for free. Cash never
|
||||
// goes below €0. The slot is freed immediately.
|
||||
export async function abandonPackage(inst: GameDb, packageId: string): Promise<{ penalty: number }> {
|
||||
const pkgRows = await inst.db.select().from(schema.packages).where(eq(schema.packages.id, packageId));
|
||||
const pkg = pkgRows[0];
|
||||
if (!pkg) throw new GameActionError(404, `package ${packageId} not found`);
|
||||
if (pkg.status !== 'loaded' && pkg.status !== 'expired') {
|
||||
throw new GameActionError(409, `package is ${pkg.status}, only loaded or expired packages can be abandoned`);
|
||||
}
|
||||
|
||||
const plane = pkg.planeId
|
||||
? (await inst.db.select().from(schema.planes).where(eq(schema.planes.id, pkg.planeId)))[0]
|
||||
: undefined;
|
||||
if (!plane) throw new GameActionError(409, `package ${packageId} is not bound to a plane`);
|
||||
if (plane.status !== 'available') {
|
||||
throw new GameActionError(409, `the plane is in flight — packages can only be abandoned while it is grounded`);
|
||||
}
|
||||
|
||||
const sim = (await inst.db.select().from(schema.simState))[0];
|
||||
if (!sim) throw new Error('sim_state row missing');
|
||||
const penalty = abandonPenalty(pkg, sim.clockMs);
|
||||
|
||||
const account = (await inst.db.select().from(schema.account))[0];
|
||||
if (!account) throw new Error('account row missing');
|
||||
await inst.db.update(schema.account).set({ cash: Math.max(0, Math.round((account.cash - penalty) * 100) / 100) });
|
||||
await inst.db.update(schema.packages).set({ status: 'abandoned', planeId: null }).where(eq(schema.packages.id, packageId));
|
||||
await persist(inst);
|
||||
return { penalty };
|
||||
}
|
||||
|
||||
// --- Market (POST /api/market/buy-plane {model}) ---
|
||||
|
||||
// Buy a catalog model at full price; it arrives 'available' with a full tank at
|
||||
@@ -132,7 +186,7 @@ export async function buyPlane(inst: GameDb, model: string): Promise<{ planeId:
|
||||
fuel: type.maxFuel, // full tank on delivery
|
||||
maxFuel: type.maxFuel,
|
||||
locationIcao: home.icao,
|
||||
contractId: null,
|
||||
destIcao: null,
|
||||
lat: home.lat,
|
||||
lon: home.lon,
|
||||
departureSimTime: null,
|
||||
|
||||
@@ -13,6 +13,8 @@ export interface PlaneType {
|
||||
// Market price in € (v0.8.0): buying costs `price`, selling pays out
|
||||
// SELL_FRACTION × price.
|
||||
price: number;
|
||||
// Cargo slot capacity (v0.12.0): how many packages can be loaded on one plane.
|
||||
capacity: number;
|
||||
}
|
||||
|
||||
export const PLANE_TYPES: Record<string, PlaneType> = {
|
||||
@@ -25,6 +27,7 @@ export const PLANE_TYPES: Record<string, PlaneType> = {
|
||||
// €200k — with the starting cash of €20k and typical hop rewards (~€1–3k),
|
||||
// a second ATR takes sustained play to afford, as intended for the MVP sink.
|
||||
price: 200_000,
|
||||
capacity: 6,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -47,6 +50,7 @@ export interface CatalogEntry {
|
||||
maxFuel: number;
|
||||
burnPerKm: number;
|
||||
speedKmh: number;
|
||||
capacity: number;
|
||||
}
|
||||
|
||||
// The catalog as a flat array, one entry per plane type — the single source of
|
||||
@@ -59,5 +63,6 @@ export function catalogEntries(): CatalogEntry[] {
|
||||
maxFuel: t.maxFuel,
|
||||
burnPerKm: t.burnPerKm,
|
||||
speedKmh: t.speedKmh,
|
||||
capacity: t.capacity,
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { abandonPenalty, abandonPenaltyPct, ABANDON_PENALTY_MIN, ABANDON_PENALTY_SPAN, elapsedFractionFor } from './penalty';
|
||||
|
||||
// The v0.12.0 abandon penalty: 15% of the payout right after creation, scaling
|
||||
// linearly to 60% at the deadline; expired packages cost nothing. Pure math —
|
||||
// the server action and the client preview both call these same functions.
|
||||
|
||||
const T0 = 1_750_000_000_000;
|
||||
const WINDOW_MS = 10 * 3_600_000; // created → deadline span
|
||||
const REWARD = 1_000;
|
||||
|
||||
const pkg = (status: string, over: Partial<{ reward: number; createdSimTime: number; deadlineSimTime: number }> = {}) => ({
|
||||
status,
|
||||
reward: REWARD,
|
||||
createdSimTime: T0,
|
||||
deadlineSimTime: T0 + WINDOW_MS,
|
||||
...over,
|
||||
});
|
||||
|
||||
describe('abandonPenaltyPct', () => {
|
||||
it('is exactly 15% at the start of the window (fraction 0)', () => {
|
||||
expect(abandonPenaltyPct(0)).toBeCloseTo(ABANDON_PENALTY_MIN, 9);
|
||||
});
|
||||
|
||||
it('is exactly 60% at the deadline (fraction 1)', () => {
|
||||
expect(abandonPenaltyPct(1)).toBeCloseTo(ABANDON_PENALTY_MIN + ABANDON_PENALTY_SPAN, 9);
|
||||
});
|
||||
|
||||
it('clamps out-of-range fractions to [0, 1]', () => {
|
||||
expect(abandonPenaltyPct(-5)).toBeCloseTo(ABANDON_PENALTY_MIN, 9);
|
||||
expect(abandonPenaltyPct(2)).toBeCloseTo(ABANDON_PENALTY_MIN + ABANDON_PENALTY_SPAN, 9);
|
||||
});
|
||||
|
||||
it('is monotonic non-decreasing across the window', () => {
|
||||
let prev = -1;
|
||||
for (let i = 0; i <= 100; i++) {
|
||||
const pct = abandonPenaltyPct(i / 100);
|
||||
expect(pct).toBeGreaterThanOrEqual(prev);
|
||||
prev = pct;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('elapsedFractionFor', () => {
|
||||
it('is 0 at creation, 0.5 at the midpoint, 1 at and past the deadline', () => {
|
||||
expect(elapsedFractionFor(T0, T0 + WINDOW_MS, T0)).toBe(0);
|
||||
expect(elapsedFractionFor(T0, T0 + WINDOW_MS, T0 + WINDOW_MS / 2)).toBeCloseTo(0.5, 9);
|
||||
expect(elapsedFractionFor(T0, T0 + WINDOW_MS, T0 + WINDOW_MS)).toBe(1);
|
||||
expect(elapsedFractionFor(T0, T0 + WINDOW_MS, T0 + WINDOW_MS * 3)).toBe(1); // clamped
|
||||
});
|
||||
|
||||
it('treats a zero/negative span as fully elapsed (max penalty)', () => {
|
||||
expect(elapsedFractionFor(T0, T0, T0)).toBe(1);
|
||||
expect(elapsedFractionFor(T0 + 5, T0, T0 + 5)).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('abandonPenalty', () => {
|
||||
it('charges exactly 15% of the payout right after creation', () => {
|
||||
expect(abandonPenalty(pkg('loaded'), T0)).toBe(Math.round(REWARD * 0.15 * 100) / 100);
|
||||
});
|
||||
|
||||
it('scales to exactly 37.5% at the midpoint and 60% at/past the deadline', () => {
|
||||
expect(abandonPenalty(pkg('loaded'), T0 + WINDOW_MS / 2)).toBe(Math.round(REWARD * 0.375 * 100) / 100);
|
||||
expect(abandonPenalty(pkg('loaded'), T0 + WINDOW_MS)).toBe(Math.round(REWARD * 0.6 * 100) / 100);
|
||||
expect(abandonPenalty(pkg('loaded'), T0 + WINDOW_MS * 2)).toBe(Math.round(REWARD * 0.6 * 100) / 100); // clamped
|
||||
});
|
||||
|
||||
it('is free for an already-expired package regardless of the clock', () => {
|
||||
expect(abandonPenalty(pkg('expired'), T0)).toBe(0);
|
||||
expect(abandonPenalty(pkg('expired'), T0 + WINDOW_MS * 5)).toBe(0);
|
||||
});
|
||||
|
||||
it('rounds to cents and scales with the reward, not a fixed amount', () => {
|
||||
// €999.99 × 15% = 149.9985 → 150.00; €333 × 60% = 199.8 exactly.
|
||||
expect(abandonPenalty(pkg('loaded', { reward: 999.99 }), T0)).toBe(150);
|
||||
expect(abandonPenalty(pkg('loaded', { reward: 333 }), T0 + WINDOW_MS)).toBe(199.8);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
// Abandon penalty (v0.12.0) — dropping a loaded package costs a fraction of its
|
||||
// payout that grows with time pressure: 15% right after creation, up to 60% at
|
||||
// the deadline. Pure function shared by the server action (lib/game/actions.ts)
|
||||
// and the client-side preview in components/RightPane.tsx so both always agree.
|
||||
|
||||
export const ABANDON_PENALTY_MIN = 0.15; // fraction of the payout, at creation time
|
||||
export const ABANDON_PENALTY_SPAN = 0.45; // added across the package's lifetime → max 60% at the deadline
|
||||
|
||||
// The penalty fraction for a given elapsedFraction ∈ [0, 1] (clamped).
|
||||
export function abandonPenaltyPct(elapsedFraction: number): number {
|
||||
const f = Math.min(1, Math.max(0, elapsedFraction));
|
||||
return ABANDON_PENALTY_MIN + ABANDON_PENALTY_SPAN * f;
|
||||
}
|
||||
|
||||
// How much of the package's lifetime has elapsed at clockMs (clamped to [0, 1]).
|
||||
export function elapsedFractionFor(createdSimTime: number, deadlineSimTime: number, clockMs: number): number {
|
||||
const span = deadlineSimTime - createdSimTime;
|
||||
if (span <= 0) return 1; // degenerate — treat as fully elapsed (max penalty)
|
||||
return Math.min(1, Math.max(0, (clockMs - createdSimTime) / span));
|
||||
}
|
||||
|
||||
// The exact € penalty for abandoning `pkg` at game time clockMs. An already-
|
||||
// EXPIRED package abandons for free; cash is floored at 0 by the caller
|
||||
// (account.cash = max(0, cash − penalty)). Rounded to cents like all money math.
|
||||
export function abandonPenalty(
|
||||
pkg: { status: string; reward: number; createdSimTime: number; deadlineSimTime: number },
|
||||
clockMs: number,
|
||||
): number {
|
||||
if (pkg.status === 'expired') return 0;
|
||||
const pct = abandonPenaltyPct(elapsedFractionFor(pkg.createdSimTime, pkg.deadlineSimTime, clockMs));
|
||||
return Math.round(pkg.reward * pct * 100) / 100;
|
||||
}
|
||||
+37
-37
@@ -4,9 +4,9 @@ import { PLANE_TYPES, STARTER_MODEL } from './catalog';
|
||||
import {
|
||||
BASE_REWARD,
|
||||
buildSeed,
|
||||
CONTRACT_COUNT_MAX,
|
||||
CONTRACT_COUNT_MIN,
|
||||
generateContract,
|
||||
PACKAGE_COUNT_MAX,
|
||||
PACKAGE_COUNT_MIN,
|
||||
generatePackage,
|
||||
HUB_ICAO,
|
||||
mulberry32,
|
||||
REWARD_PER_KM,
|
||||
@@ -41,7 +41,7 @@ describe('buildSeed', () => {
|
||||
fuel: type.maxFuel,
|
||||
maxFuel: type.maxFuel,
|
||||
locationIcao: HUB_ICAO,
|
||||
contractId: null,
|
||||
destIcao: null,
|
||||
lat: 50.0333,
|
||||
lon: 8.5706,
|
||||
});
|
||||
@@ -52,13 +52,13 @@ describe('buildSeed', () => {
|
||||
expect(seed.plane.locationIcao).toBe(AIRPORTS[1].icao);
|
||||
});
|
||||
|
||||
it('seeds 8–12 open contracts between distinct fixture airports', () => {
|
||||
it('seeds 8–12 open packages between distinct fixture airports', () => {
|
||||
const seed = seedWith(42);
|
||||
expect(seed.contracts.length).toBeGreaterThanOrEqual(CONTRACT_COUNT_MIN);
|
||||
expect(seed.contracts.length).toBeLessThanOrEqual(CONTRACT_COUNT_MAX);
|
||||
expect(seed.packages.length).toBeGreaterThanOrEqual(PACKAGE_COUNT_MIN);
|
||||
expect(seed.packages.length).toBeLessThanOrEqual(PACKAGE_COUNT_MAX);
|
||||
|
||||
const icaoSet = new Set(AIRPORTS.map((a) => a.icao));
|
||||
for (const c of seed.contracts) {
|
||||
for (const c of seed.packages) {
|
||||
expect(icaoSet.has(c.originIcao)).toBe(true);
|
||||
expect(icaoSet.has(c.destIcao)).toBe(true);
|
||||
expect(c.originIcao).not.toBe(c.destIcao);
|
||||
@@ -66,12 +66,12 @@ describe('buildSeed', () => {
|
||||
expect(c.planeId).toBeNull();
|
||||
expect(c.createdSimTime).toBe(NOW);
|
||||
}
|
||||
expect(new Set(seed.contracts.map((c) => c.id)).size).toBe(seed.contracts.length);
|
||||
expect(new Set(seed.packages.map((c) => c.id)).size).toBe(seed.packages.length);
|
||||
});
|
||||
|
||||
it('scales reward by haversine distance: round(500 + 2.5 * km)', () => {
|
||||
const seed = seedWith(42);
|
||||
for (const c of seed.contracts) {
|
||||
for (const c of seed.packages) {
|
||||
const o = AIRPORTS.find((a) => a.icao === c.originIcao)!;
|
||||
const d = AIRPORTS.find((a) => a.icao === c.destIcao)!;
|
||||
expect(c.reward).toBe(Math.round(BASE_REWARD + REWARD_PER_KM * haversineKm(o.lat, o.lon, d.lat, d.lon)));
|
||||
@@ -80,7 +80,7 @@ describe('buildSeed', () => {
|
||||
|
||||
it('sets deadlines inside the 6–72h game-time window after now', () => {
|
||||
const seed = seedWith(42);
|
||||
for (const c of seed.contracts) {
|
||||
for (const c of seed.packages) {
|
||||
expect(c.deadlineSimTime).toBeGreaterThan(NOW + 6 * 3_600_000 - 1);
|
||||
expect(c.deadlineSimTime).toBeLessThanOrEqual(NOW + 72 * 3_600_000);
|
||||
}
|
||||
@@ -97,8 +97,8 @@ describe('buildSeed', () => {
|
||||
expect(seedWith(42)).toEqual(seedWith(42));
|
||||
});
|
||||
|
||||
it('produces different contracts for a different RNG seed', () => {
|
||||
expect(seedWith(1).contracts).not.toEqual(seedWith(2).contracts);
|
||||
it('produces different packages for a different RNG seed', () => {
|
||||
expect(seedWith(1).packages).not.toEqual(seedWith(2).packages);
|
||||
});
|
||||
|
||||
it('rejects an airport list too small to form a route', () => {
|
||||
@@ -111,9 +111,9 @@ describe('buildSeed', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateContract (shared seed/spawn builder)', () => {
|
||||
it('builds an open contract between distinct fixture airports with the reward formula', () => {
|
||||
const c = generateContract({ id: 'c-x', airports: AIRPORTS, rng: mulberry32(42), nowMs: NOW });
|
||||
describe('generatePackage (shared seed/spawn builder)', () => {
|
||||
it('builds an open package between distinct fixture airports with the reward formula', () => {
|
||||
const c = generatePackage({ id: 'c-x', airports: AIRPORTS, rng: mulberry32(42), nowMs: NOW });
|
||||
|
||||
expect(c.id).toBe('c-x');
|
||||
expect(c.status).toBe('open');
|
||||
@@ -134,39 +134,39 @@ describe('generateContract (shared seed/spawn builder)', () => {
|
||||
});
|
||||
|
||||
it('is deterministic for a fixed RNG and honors the id/nowMs inputs', () => {
|
||||
const a = generateContract({ id: 'c-1', airports: AIRPORTS, rng: mulberry32(7), nowMs: NOW });
|
||||
const b = generateContract({ id: 'c-1', airports: AIRPORTS, rng: mulberry32(7), nowMs: NOW });
|
||||
const a = generatePackage({ id: 'c-1', airports: AIRPORTS, rng: mulberry32(7), nowMs: NOW });
|
||||
const b = generatePackage({ id: 'c-1', airports: AIRPORTS, rng: mulberry32(7), nowMs: NOW });
|
||||
expect(a).toEqual(b);
|
||||
|
||||
const c = generateContract({ id: 'c-2', airports: AIRPORTS, rng: mulberry32(8), nowMs: NOW + 1000 });
|
||||
const c = generatePackage({ id: 'c-2', airports: AIRPORTS, rng: mulberry32(8), nowMs: NOW + 1000 });
|
||||
expect(c.id).toBe('c-2');
|
||||
expect(c.createdSimTime).toBe(NOW + 1000);
|
||||
expect(c.deadlineSimTime).not.toBe(a.deadlineSimTime); // different RNG/now → different contract
|
||||
expect(c.deadlineSimTime).not.toBe(a.deadlineSimTime); // different RNG/now → different package
|
||||
});
|
||||
|
||||
it('deadlineOffsetMs pins the deadline to now + offset (e2e expiry hook)', () => {
|
||||
const c = generateContract({ id: 'c-hook', airports: AIRPORTS, rng: mulberry32(1), nowMs: NOW, deadlineOffsetMs: 10_000 });
|
||||
const c = generatePackage({ id: 'c-hook', airports: AIRPORTS, rng: mulberry32(1), nowMs: NOW, deadlineOffsetMs: 10_000 });
|
||||
expect(c.deadlineSimTime).toBe(NOW + 10_000);
|
||||
});
|
||||
|
||||
it('buildSeed contracts are exactly the shared builder output (spawn matches seed)', () => {
|
||||
it('buildSeed packages are exactly the shared builder output (spawn matches seed)', () => {
|
||||
const rngA = mulberry32(42);
|
||||
const count = CONTRACT_COUNT_MIN + Math.floor(rngA() * (CONTRACT_COUNT_MAX - CONTRACT_COUNT_MIN + 1));
|
||||
const count = PACKAGE_COUNT_MIN + Math.floor(rngA() * (PACKAGE_COUNT_MAX - PACKAGE_COUNT_MIN + 1));
|
||||
const expected: string[] = [];
|
||||
for (let i = 0; i < count; i++) {
|
||||
expected.push(JSON.stringify(generateContract({ id: `contract-${i + 1}`, airports: AIRPORTS, rng: rngA, nowMs: NOW })));
|
||||
expected.push(JSON.stringify(generatePackage({ id: `package-${i + 1}`, airports: AIRPORTS, rng: rngA, nowMs: NOW })));
|
||||
}
|
||||
const seed = buildSeed({ airports: AIRPORTS, rng: mulberry32(42), nowMs: NOW });
|
||||
expect(seed.contracts.map((c) => JSON.stringify(c))).toEqual(expected);
|
||||
expect(seed.packages.map((c) => JSON.stringify(c))).toEqual(expected);
|
||||
});
|
||||
|
||||
it('rejects an airport list too small to form a route', () => {
|
||||
expect(() => generateContract({ id: 'c-x', airports: AIRPORTS.slice(0, 1), rng: mulberry32(42), nowMs: NOW })).toThrow();
|
||||
expect(() => generatePackage({ id: 'c-x', airports: AIRPORTS.slice(0, 1), rng: mulberry32(42), nowMs: NOW })).toThrow();
|
||||
});
|
||||
|
||||
describe('forced endpoints (v0.8.0 spawn coverage + test hook)', () => {
|
||||
it('originIcao forces the origin; dest stays random but distinct', () => {
|
||||
const c = generateContract({ id: 'c-o', airports: AIRPORTS, rng: mulberry32(42), nowMs: NOW, originIcao: 'EDDF' });
|
||||
const c = generatePackage({ id: 'c-o', airports: AIRPORTS, rng: mulberry32(42), nowMs: NOW, originIcao: 'EDDF' });
|
||||
expect(c.originIcao).toBe('EDDF');
|
||||
expect(c.destIcao).not.toBe('EDDF');
|
||||
|
||||
@@ -176,13 +176,13 @@ describe('generateContract (shared seed/spawn builder)', () => {
|
||||
});
|
||||
|
||||
it('destIcao forces the destination; origin stays random but distinct', () => {
|
||||
const c = generateContract({ id: 'c-d', airports: AIRPORTS, rng: mulberry32(42), nowMs: NOW, destIcao: 'LEBC' });
|
||||
const c = generatePackage({ id: 'c-d', airports: AIRPORTS, rng: mulberry32(42), nowMs: NOW, destIcao: 'LEBC' });
|
||||
expect(c.destIcao).toBe('LEBC');
|
||||
expect(c.originIcao).not.toBe('LEBC');
|
||||
});
|
||||
|
||||
it('both forced → the exact requested route with the distance-based reward', () => {
|
||||
const c = generateContract({ id: 'c-b', airports: AIRPORTS, rng: mulberry32(42), nowMs: NOW, originIcao: 'EDDF', destIcao: 'EHAM' });
|
||||
const c = generatePackage({ id: 'c-b', airports: AIRPORTS, rng: mulberry32(42), nowMs: NOW, originIcao: 'EDDF', destIcao: 'EHAM' });
|
||||
expect(c.originIcao).toBe('EDDF');
|
||||
expect(c.destIcao).toBe('EHAM');
|
||||
|
||||
@@ -192,22 +192,22 @@ describe('generateContract (shared seed/spawn builder)', () => {
|
||||
});
|
||||
|
||||
it('is deterministic for a fixed RNG with forced endpoints', () => {
|
||||
const a = generateContract({ id: 'c-1', airports: AIRPORTS, rng: mulberry32(7), nowMs: NOW, originIcao: 'EDDF' });
|
||||
const b = generateContract({ id: 'c-1', airports: AIRPORTS, rng: mulberry32(7), nowMs: NOW, originIcao: 'EDDF' });
|
||||
const a = generatePackage({ id: 'c-1', airports: AIRPORTS, rng: mulberry32(7), nowMs: NOW, originIcao: 'EDDF' });
|
||||
const b = generatePackage({ id: 'c-1', airports: AIRPORTS, rng: mulberry32(7), nowMs: NOW, originIcao: 'EDDF' });
|
||||
expect(a).toEqual(b);
|
||||
});
|
||||
|
||||
it('throws on an unknown forced ICAO or identical endpoints', () => {
|
||||
expect(() => generateContract({ id: 'c-x', airports: AIRPORTS, rng: mulberry32(1), nowMs: NOW, originIcao: 'XXXX' })).toThrow(/unknown origin/);
|
||||
expect(() => generateContract({ id: 'c-x', airports: AIRPORTS, rng: mulberry32(1), nowMs: NOW, destIcao: 'XXXX' })).toThrow(/unknown destination/);
|
||||
expect(() => generateContract({ id: 'c-x', airports: AIRPORTS, rng: mulberry32(1), nowMs: NOW, originIcao: 'EDDF', destIcao: 'EDDF' })).toThrow(/must differ/);
|
||||
expect(() => generatePackage({ id: 'c-x', airports: AIRPORTS, rng: mulberry32(1), nowMs: NOW, originIcao: 'XXXX' })).toThrow(/unknown origin/);
|
||||
expect(() => generatePackage({ id: 'c-x', airports: AIRPORTS, rng: mulberry32(1), nowMs: NOW, destIcao: 'XXXX' })).toThrow(/unknown destination/);
|
||||
expect(() => generatePackage({ id: 'c-x', airports: AIRPORTS, rng: mulberry32(1), nowMs: NOW, originIcao: 'EDDF', destIcao: 'EDDF' })).toThrow(/must differ/);
|
||||
});
|
||||
|
||||
it('omitting both endpoints keeps the pre-v0.8.0 RNG call order (byte-identical output)', () => {
|
||||
// Same seed as a historical unforced call → same contract, proving forced
|
||||
// Same seed as a historical unforced call → same package, proving forced
|
||||
// endpoints consume no extra RNG draws when absent.
|
||||
const a = generateContract({ id: 'c-x', airports: AIRPORTS, rng: mulberry32(42), nowMs: NOW });
|
||||
const b = generateContract({ id: 'c-x', airports: AIRPORTS, rng: mulberry32(42), nowMs: NOW, originIcao: undefined, destIcao: undefined });
|
||||
const a = generatePackage({ id: 'c-x', airports: AIRPORTS, rng: mulberry32(42), nowMs: NOW });
|
||||
const b = generatePackage({ id: 'c-x', airports: AIRPORTS, rng: mulberry32(42), nowMs: NOW, originIcao: undefined, destIcao: undefined });
|
||||
expect(a).toEqual(b);
|
||||
});
|
||||
});
|
||||
|
||||
+21
-21
@@ -23,7 +23,7 @@ export function mulberry32(seed: number): Rng {
|
||||
a |= 0;
|
||||
a = (a + 0x6d2b79f5) | 0;
|
||||
let t = Math.imul(a ^ (a >>> 15), 1 | a);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
t = (t + Math.imul(t ^ (a >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
@@ -35,12 +35,12 @@ export interface SeedPlane {
|
||||
fuel: number;
|
||||
maxFuel: number;
|
||||
locationIcao: string;
|
||||
contractId: null;
|
||||
destIcao: null;
|
||||
lat: number;
|
||||
lon: number;
|
||||
}
|
||||
|
||||
export interface SeedContract {
|
||||
export interface SeedPackage {
|
||||
id: string;
|
||||
originIcao: string;
|
||||
destIcao: string;
|
||||
@@ -55,7 +55,7 @@ export interface SeedContract {
|
||||
|
||||
export interface SeedData {
|
||||
plane: SeedPlane;
|
||||
contracts: SeedContract[];
|
||||
packages: SeedPackage[];
|
||||
account: { cash: number; reputation: number };
|
||||
simState: { clockMs: number; timeScale: number; paused: false; lastRealTickMs: number };
|
||||
}
|
||||
@@ -70,19 +70,19 @@ export const STARTING_REPUTATION = 10;
|
||||
// failing first run. (EDDF = Frankfurt; EDDM is Munich — don't mix them up.)
|
||||
export const HUB_ICAO = 'EDDF'; // Frankfurt Main
|
||||
|
||||
export const CONTRACT_COUNT_MIN = 8;
|
||||
export const CONTRACT_COUNT_MAX = 12; // inclusive
|
||||
export const PACKAGE_COUNT_MIN = 8;
|
||||
export const PACKAGE_COUNT_MAX = 12; // inclusive
|
||||
|
||||
// Market target (v0.7.0): the sim engine tops open contracts back up to this
|
||||
// Market target (v0.7.0): the sim engine tops open packages back up to this
|
||||
// count after expiries, so the job board never runs dry.
|
||||
export const MARKET_TARGET_OPEN_CONTRACTS = 10;
|
||||
export const MARKET_TARGET_OPEN_PACKAGES = 10;
|
||||
|
||||
// Reward formula (v0.6.0 — deliberately simple; real revenue/cost modeling is a
|
||||
// later increment): reward = BASE_REWARD + REWARD_PER_KM * great-circle km.
|
||||
export const BASE_REWARD = 500;
|
||||
export const REWARD_PER_KM = 2.5;
|
||||
|
||||
// Contract deadlines: now + a plausible game-time window of 6–72 hours.
|
||||
// Package deadlines: now + a plausible game-time window of 6–72 hours.
|
||||
const DEADLINE_MIN_HOURS = 6;
|
||||
const DEADLINE_MAX_HOURS = 72;
|
||||
|
||||
@@ -92,16 +92,16 @@ export function rewardForDistanceKm(km: number): number {
|
||||
return Math.round(BASE_REWARD + REWARD_PER_KM * km);
|
||||
}
|
||||
|
||||
// Shared contract generator, used by BOTH the first-run seed and the runtime
|
||||
// market spawn (v0.7.0) so spawned contracts match seeded ones exactly: random
|
||||
// Shared package generator, used by BOTH the first-run seed and the runtime
|
||||
// market spawn (v0.7.0) so spawned packages match seeded ones exactly: random
|
||||
// distinct airports from the dataset, distance-based reward, cargo flavor,
|
||||
// deadline now + 6–72h game time (or now + deadlineOffsetMs when given — used by
|
||||
// the e2e test hook to force a near-term expiry). The RNG call order per contract
|
||||
// the e2e test hook to force a near-term expiry). The RNG call order per package
|
||||
// is fixed: origin, dest, cargoType, cargoCount, [deadline window].
|
||||
// v0.8.0: originIcao/destIcao optionally FORCE an endpoint (spawn coverage rule +
|
||||
// the e2e create-contract hook); a forced endpoint consumes no RNG draws, so
|
||||
// the e2e create-package hook); a forced endpoint consumes no RNG draws, so
|
||||
// callers that omit both get byte-identical behavior to before.
|
||||
export function generateContract(input: {
|
||||
export function generatePackage(input: {
|
||||
id: string;
|
||||
airports: SeedAirport[];
|
||||
rng: Rng;
|
||||
@@ -109,9 +109,9 @@ export function generateContract(input: {
|
||||
deadlineOffsetMs?: number;
|
||||
originIcao?: string;
|
||||
destIcao?: string;
|
||||
}): SeedContract {
|
||||
}): SeedPackage {
|
||||
const { airports, rng, nowMs } = input;
|
||||
if (airports.length < 2) throw new Error('contract generation needs at least two airports');
|
||||
if (airports.length < 2) throw new Error('package generation needs at least two airports');
|
||||
|
||||
let oi: number;
|
||||
if (input.originIcao !== undefined) {
|
||||
@@ -179,22 +179,22 @@ export function buildSeed(input: {
|
||||
fuel: type.maxFuel, // starts full
|
||||
maxFuel: type.maxFuel,
|
||||
locationIcao: hub.icao,
|
||||
contractId: null,
|
||||
destIcao: null,
|
||||
lat: hub.lat,
|
||||
lon: hub.lon,
|
||||
};
|
||||
|
||||
const count = CONTRACT_COUNT_MIN + Math.floor(rng() * (CONTRACT_COUNT_MAX - CONTRACT_COUNT_MIN + 1));
|
||||
const count = PACKAGE_COUNT_MIN + Math.floor(rng() * (PACKAGE_COUNT_MAX - PACKAGE_COUNT_MIN + 1));
|
||||
// Stable index-based ids for the seed set; runtime-generated entities must use
|
||||
// random UUIDs to avoid colliding with these.
|
||||
const contracts: SeedContract[] = [];
|
||||
const packages: SeedPackage[] = [];
|
||||
for (let i = 0; i < count; i++) {
|
||||
contracts.push(generateContract({ id: `contract-${i + 1}`, airports, rng, nowMs }));
|
||||
packages.push(generatePackage({ id: `package-${i + 1}`, airports, rng, nowMs }));
|
||||
}
|
||||
|
||||
return {
|
||||
plane,
|
||||
contracts,
|
||||
packages,
|
||||
account: { cash: STARTING_CASH, reputation: STARTING_REPUTATION },
|
||||
// lastRealTickMs starts at the seed moment so the first tick-on-read advances
|
||||
// by ~0 instead of treating "time since install" as elapsed play time.
|
||||
|
||||
+29
-27
@@ -15,15 +15,18 @@ export interface PlaneState {
|
||||
maxFuel: number;
|
||||
locationIcao: string;
|
||||
locationName: string;
|
||||
contractId: string | null;
|
||||
// Current flight destination (v0.12.0) — set by fly, null when grounded. The
|
||||
// origin of the current leg is always locationIcao while flying.
|
||||
destIcao: string | null;
|
||||
destName: string | null;
|
||||
// Sim-clock departure time of the current flight (v0.8.0) — null when grounded,
|
||||
// set by dispatch while flying so clients can compute progress/ETA from the clock.
|
||||
// set by fly while flying so clients can compute progress/ETA from the clock.
|
||||
departureSimTime: number | null;
|
||||
lat: number;
|
||||
lon: number;
|
||||
}
|
||||
|
||||
export interface ContractState {
|
||||
export interface PackageState {
|
||||
id: string;
|
||||
originIcao: string;
|
||||
originName: string;
|
||||
@@ -33,7 +36,7 @@ export interface ContractState {
|
||||
cargoType: string;
|
||||
cargoCount: number;
|
||||
deadlineSimTime: number;
|
||||
status: 'open' | 'accepted' | 'completed' | 'expired';
|
||||
status: 'open' | 'loaded' | 'delivered' | 'expired' | 'abandoned';
|
||||
planeId: string | null;
|
||||
createdSimTime: number;
|
||||
}
|
||||
@@ -42,7 +45,7 @@ export interface StateSnapshot {
|
||||
account: { cash: number; reputation: number };
|
||||
simState: { clockMs: number; timeScale: number; paused: boolean };
|
||||
planes: PlaneState[];
|
||||
contracts: ContractState[];
|
||||
packages: PackageState[];
|
||||
// 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.
|
||||
catalog: CatalogEntry[];
|
||||
@@ -55,11 +58,11 @@ export async function getStateSnapshot(): Promise<StateSnapshot> {
|
||||
// NOTE: use plain select(), not the relational db.query.* API — in drizzle-orm
|
||||
// 0.45.x the sql-js driver drops the result mapper for relational queries and
|
||||
// returns raw rows keyed by SQL column names (snake_case, no type decoding).
|
||||
const [accountRows, simRows, planeRows, contractRows] = await Promise.all([
|
||||
const [accountRows, simRows, planeRows, packageRows] = await Promise.all([
|
||||
db.select().from(schema.account),
|
||||
db.select().from(schema.simState),
|
||||
db.select().from(schema.planes),
|
||||
db.select().from(schema.contracts),
|
||||
db.select().from(schema.packages),
|
||||
]);
|
||||
const accountRow = accountRows[0];
|
||||
const simRow = simRows[0];
|
||||
@@ -72,14 +75,12 @@ export async function getStateSnapshot(): Promise<StateSnapshot> {
|
||||
|
||||
// Analytic movement (v0.7.0): a flying plane's stored lat/lon/fuel are its
|
||||
// departure values — live position and fuel are pure functions of the clock.
|
||||
const contractById = new Map(contractRows.map((c) => [c.id, c]));
|
||||
const livePlane = (p: schema.PlaneRow) => {
|
||||
if (p.status !== 'flying' || p.departureSimTime == null || !p.contractId) return null;
|
||||
const contract = contractById.get(p.contractId);
|
||||
if (p.status !== 'flying' || p.departureSimTime == null || !p.destIcao) return null;
|
||||
const type = PLANE_TYPES[p.model];
|
||||
const from = contract ? coordsByIcao.get(contract.originIcao) : undefined;
|
||||
const to = contract ? coordsByIcao.get(contract.destIcao) : undefined;
|
||||
if (!contract || !type || !from || !to) return null;
|
||||
const from = coordsByIcao.get(p.locationIcao);
|
||||
const to = coordsByIcao.get(p.destIcao);
|
||||
if (!type || !from || !to) return null;
|
||||
const distanceKm = haversineKm(from.lat, from.lon, to.lat, to.lon);
|
||||
const progress = progressAt(p.departureSimTime, distanceKm, type.speedKmh, simRow.clockMs);
|
||||
const pos = positionAt(from.lat, from.lon, to.lat, to.lon, progress);
|
||||
@@ -102,25 +103,26 @@ export async function getStateSnapshot(): Promise<StateSnapshot> {
|
||||
maxFuel: p.maxFuel,
|
||||
locationIcao: p.locationIcao,
|
||||
locationName: nameOf(p.locationIcao),
|
||||
contractId: p.contractId,
|
||||
destIcao: p.destIcao,
|
||||
destName: p.destIcao ? nameOf(p.destIcao) : null,
|
||||
departureSimTime: p.departureSimTime,
|
||||
lat: live?.lat ?? p.lat,
|
||||
lon: live?.lon ?? p.lon,
|
||||
};
|
||||
}),
|
||||
contracts: contractRows.map((c) => ({
|
||||
id: c.id,
|
||||
originIcao: c.originIcao,
|
||||
originName: nameOf(c.originIcao),
|
||||
destIcao: c.destIcao,
|
||||
destName: nameOf(c.destIcao),
|
||||
reward: c.reward,
|
||||
cargoType: c.cargoType,
|
||||
cargoCount: c.cargoCount,
|
||||
deadlineSimTime: c.deadlineSimTime,
|
||||
status: c.status,
|
||||
planeId: c.planeId,
|
||||
createdSimTime: c.createdSimTime,
|
||||
packages: packageRows.map((p) => ({
|
||||
id: p.id,
|
||||
originIcao: p.originIcao,
|
||||
originName: nameOf(p.originIcao),
|
||||
destIcao: p.destIcao,
|
||||
destName: nameOf(p.destIcao),
|
||||
reward: p.reward,
|
||||
cargoType: p.cargoType,
|
||||
cargoCount: p.cargoCount,
|
||||
deadlineSimTime: p.deadlineSimTime,
|
||||
status: p.status,
|
||||
planeId: p.planeId,
|
||||
createdSimTime: p.createdSimTime,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
+36
-52
@@ -13,8 +13,10 @@ function snapshot(overrides: Partial<StateSnapshot> = {}): StateSnapshot {
|
||||
account: { cash: 0, reputation: 0 },
|
||||
simState: { clockMs: 0, timeScale: 1, paused: false },
|
||||
planes: [],
|
||||
contracts: [],
|
||||
catalog: [{ model: 'atr72', label: 'ATR 72-600', price: 200_000, maxFuel: 6300, burnPerKm: 1.75, speedKmh: 510 }],
|
||||
packages: [],
|
||||
catalog: [
|
||||
{ model: 'atr72', label: 'ATR 72-600', price: 200_000, maxFuel: 6300, burnPerKm: 1.75, speedKmh: 510, capacity: 6 },
|
||||
],
|
||||
fuelPricePerL: 0.8,
|
||||
sellFraction: 0.5,
|
||||
...overrides,
|
||||
@@ -30,11 +32,8 @@ describe('planesGeoJson', () => {
|
||||
const fc = planesGeoJson(
|
||||
snapshot({
|
||||
planes: [
|
||||
{ id: 'plane-starter', model: 'atr72', status: 'available', fuel: 6300, maxFuel: 6300, locationIcao: 'EDDF', locationName: 'Frankfurt Main Airport', contractId: null, departureSimTime: null, lat: 50.03, lon: 8.56 },
|
||||
{ id: 'plane-2', model: 'atr72', status: 'flying', fuel: 4000, maxFuel: 6300, locationIcao: 'EDDF', locationName: 'Frankfurt Main Airport', contractId: 'c1', departureSimTime: 1000, lat: 51.2, lon: 9.1 },
|
||||
],
|
||||
contracts: [
|
||||
{ id: 'c1', originIcao: 'EDDF', originName: 'Frankfurt Main Airport', destIcao: 'EDDV', destName: 'Hannover Airport', reward: 100, cargoType: 'mail', cargoCount: 5, deadlineSimTime: 9e8, status: 'accepted', planeId: 'plane-2', createdSimTime: 0 },
|
||||
{ id: 'plane-starter', model: 'atr72', status: 'available', fuel: 6300, maxFuel: 6300, locationIcao: 'EDDF', locationName: 'Frankfurt Main Airport', destIcao: null, destName: null, departureSimTime: null, lat: 50.03, lon: 8.56 },
|
||||
{ id: 'plane-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 },
|
||||
],
|
||||
}),
|
||||
);
|
||||
@@ -52,7 +51,7 @@ describe('planesGeoJson', () => {
|
||||
expect(flying.properties.flying).toBe(true);
|
||||
expect(flying.properties.status).toBe('flying');
|
||||
expect(flying.properties.fuelText).toBe('4000 / 6300 L');
|
||||
expect(flying.properties.routeText).toBe('Frankfurt Main Airport → Hannover Airport');
|
||||
expect(flying.properties.routeText).toBe('Frankfurt Main Airport → Hannover Airport'); // from the plane's own dest fields (v0.12.0)
|
||||
});
|
||||
|
||||
it('falls back to the raw model id when the catalog has no entry', () => {
|
||||
@@ -60,18 +59,18 @@ describe('planesGeoJson', () => {
|
||||
snapshot({
|
||||
catalog: [],
|
||||
planes: [
|
||||
{ id: 'p1', model: 'mystery', status: 'available', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'x', contractId: null, departureSimTime: null, lat: 0, lon: 0 },
|
||||
{ id: 'p1', model: 'mystery', status: 'available', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'x', destIcao: null, destName: null, departureSimTime: null, lat: 0, lon: 0 },
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(fc.features[0].properties.modelLabel).toBe('mystery');
|
||||
});
|
||||
|
||||
it('leaves routeText empty for a flying plane whose contract is missing from the snapshot', () => {
|
||||
it('leaves routeText empty for a flying plane without a destination name', () => {
|
||||
const fc = planesGeoJson(
|
||||
snapshot({
|
||||
planes: [
|
||||
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'x', contractId: 'gone', departureSimTime: 0, lat: 0, lon: 0 },
|
||||
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'x', destIcao: null, destName: null, departureSimTime: 0, lat: 0, lon: 0 },
|
||||
],
|
||||
}),
|
||||
);
|
||||
@@ -79,77 +78,62 @@ describe('planesGeoJson', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('routesGeoJson', () => {
|
||||
describe('routesGeoJson (v0.12.0 — one line per flying plane\'s current leg)', () => {
|
||||
it('returns an empty collection for a null snapshot', () => {
|
||||
expect(routesGeoJson(null, AIRPORTS)).toEqual({ type: 'FeatureCollection', features: [] });
|
||||
});
|
||||
|
||||
it('draws nothing for open/completed/expired contracts', () => {
|
||||
const mk = (status: string) => ({ id: `c-${status}`, originIcao: 'EDDF', originName: 'F', destIcao: 'EDDV', destName: 'H', reward: 1, cargoType: 'mail', cargoCount: 1, deadlineSimTime: 9e8, status, planeId: null, createdSimTime: 0 });
|
||||
it('draws nothing for grounded planes, whatever their packages', () => {
|
||||
const fc = routesGeoJson(
|
||||
snapshot({ contracts: [mk('open'), mk('completed'), mk('expired')] as StateSnapshot['contracts'] }),
|
||||
snapshot({
|
||||
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 },
|
||||
],
|
||||
}),
|
||||
AIRPORTS,
|
||||
);
|
||||
expect(fc.features).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('accepted-but-undispatched contract → pending line origin→dest', () => {
|
||||
it('flying plane → one line origin→dest_icao with the plane id', () => {
|
||||
const fc = routesGeoJson(
|
||||
snapshot({
|
||||
contracts: [
|
||||
{ id: 'c1', originIcao: 'EDDF', originName: 'F', destIcao: 'EHAM', destName: 'A', reward: 1, cargoType: 'mail', cargoCount: 1, deadlineSimTime: 9e8, status: 'accepted', planeId: null, createdSimTime: 0 },
|
||||
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 },
|
||||
],
|
||||
}),
|
||||
AIRPORTS,
|
||||
);
|
||||
expect(fc.features).toHaveLength(1);
|
||||
expect(fc.features[0].properties).toEqual({ contractId: 'c1', kind: 'pending' });
|
||||
expect(fc.features[0].properties).toEqual({ planeId: 'p1' });
|
||||
expect(fc.features[0].geometry.coordinates).toEqual([
|
||||
[8.56, 50.03], // EDDF [lon, lat]
|
||||
[4.76, 52.31], // EHAM
|
||||
]);
|
||||
});
|
||||
|
||||
it('accepted + plane flying → inflight line', () => {
|
||||
it('skips a flying plane whose endpoint is missing from the airport dataset', () => {
|
||||
const fc = routesGeoJson(
|
||||
snapshot({
|
||||
planes: [
|
||||
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', contractId: 'c1', departureSimTime: 0, lat: 51, lon: 9 },
|
||||
],
|
||||
contracts: [
|
||||
{ id: 'c1', originIcao: 'EDDF', originName: 'F', destIcao: 'EDDV', destName: 'H', reward: 1, cargoType: 'mail', cargoCount: 1, deadlineSimTime: 9e8, status: 'accepted', planeId: 'p1', createdSimTime: 0 },
|
||||
],
|
||||
}),
|
||||
AIRPORTS,
|
||||
);
|
||||
expect(fc.features).toHaveLength(1);
|
||||
expect(fc.features[0].properties.kind).toBe('inflight');
|
||||
});
|
||||
|
||||
it('accepted + planeId set but plane grounded → still pending (defensive)', () => {
|
||||
const fc = routesGeoJson(
|
||||
snapshot({
|
||||
planes: [
|
||||
{ id: 'p1', model: 'atr72', status: 'available', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', contractId: null, departureSimTime: null, lat: 50.03, lon: 8.56 },
|
||||
],
|
||||
contracts: [
|
||||
{ id: 'c1', originIcao: 'EDDF', originName: 'F', destIcao: 'EDDV', destName: 'H', reward: 1, cargoType: 'mail', cargoCount: 1, deadlineSimTime: 9e8, status: 'accepted', planeId: 'p1', createdSimTime: 0 },
|
||||
],
|
||||
}),
|
||||
AIRPORTS,
|
||||
);
|
||||
expect(fc.features[0].properties.kind).toBe('pending');
|
||||
});
|
||||
|
||||
it('skips a contract whose endpoint is missing from the airport dataset', () => {
|
||||
const fc = routesGeoJson(
|
||||
snapshot({
|
||||
contracts: [
|
||||
{ id: 'c1', originIcao: 'ZZZZ', originName: '?', destIcao: 'EDDV', destName: 'H', reward: 1, cargoType: 'mail', cargoCount: 1, deadlineSimTime: 9e8, status: 'accepted', planeId: null, createdSimTime: 0 },
|
||||
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'ZZZZ', locationName: '?', destIcao: 'EDDV', destName: 'H', departureSimTime: 0, lat: 0, lon: 0 },
|
||||
],
|
||||
}),
|
||||
AIRPORTS,
|
||||
);
|
||||
expect(fc.features).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('one line per flying plane — multiple planes draw multiple legs', () => {
|
||||
const fc = routesGeoJson(
|
||||
snapshot({
|
||||
planes: [
|
||||
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', destIcao: 'EDDV', destName: 'H', departureSimTime: 0, lat: 51, lon: 9 },
|
||||
{ id: '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 },
|
||||
],
|
||||
}),
|
||||
AIRPORTS,
|
||||
);
|
||||
expect(fc.features.map((f) => f.properties.planeId).sort()).toEqual(['p1', 'p2']);
|
||||
});
|
||||
});
|
||||
|
||||
+14
-18
@@ -1,9 +1,10 @@
|
||||
import type { StateSnapshot } from './game/state';
|
||||
import { formatFuel } from './format';
|
||||
|
||||
// Pure GeoJSON builders for the map's dynamic layers (v0.11.0): one Point feature
|
||||
// per plane, one LineString per accepted/in-flight contract. Kept out of
|
||||
// components/Map.tsx so the classification logic is unit-testable without a DOM.
|
||||
// Pure GeoJSON builders for the map's dynamic layers (v0.11.0, package model
|
||||
// v0.12.0): one Point feature per plane, one LineString per FLYING plane's
|
||||
// current leg (origin → dest_icao). Kept out of components/Map.tsx so the
|
||||
// classification logic is unit-testable without a DOM.
|
||||
|
||||
export interface PlaneFeatureProps {
|
||||
id: string;
|
||||
@@ -15,8 +16,7 @@ export interface PlaneFeatureProps {
|
||||
}
|
||||
|
||||
export interface RouteFeatureProps {
|
||||
contractId: string;
|
||||
kind: 'pending' | 'inflight';
|
||||
planeId: string;
|
||||
}
|
||||
|
||||
export interface MapPointFeature {
|
||||
@@ -41,12 +41,10 @@ const EMPTY_LINES: FeatureCollection<MapLineFeature> = { type: 'FeatureCollectio
|
||||
|
||||
export function planesGeoJson(state: StateSnapshot | null): FeatureCollection<MapPointFeature> {
|
||||
if (!state) return EMPTY_POINTS;
|
||||
const contractById = new Map(state.contracts.map((c) => [c.id, c]));
|
||||
// Catalog display name ("ATR 72-600") for the popup — raw model id as fallback.
|
||||
const labelByModel = new Map(state.catalog.map((e) => [e.model, e.label]));
|
||||
const features: MapPointFeature[] = state.planes.map((p) => {
|
||||
const flying = p.status === 'flying';
|
||||
const contract = p.contractId ? contractById.get(p.contractId) : undefined;
|
||||
return {
|
||||
type: 'Feature',
|
||||
geometry: { type: 'Point', coordinates: [p.lon, p.lat] },
|
||||
@@ -55,7 +53,7 @@ export function planesGeoJson(state: StateSnapshot | null): FeatureCollection<Ma
|
||||
modelLabel: labelByModel.get(p.model) ?? p.model,
|
||||
status: p.status,
|
||||
fuelText: formatFuel(p.fuel, p.maxFuel),
|
||||
routeText: flying && contract ? `${contract.originName} → ${contract.destName}` : '',
|
||||
routeText: flying && p.destName ? `${p.locationName} → ${p.destName}` : '',
|
||||
flying,
|
||||
},
|
||||
};
|
||||
@@ -69,22 +67,20 @@ export interface AirportCoord {
|
||||
lon: number;
|
||||
}
|
||||
|
||||
// One LineString per contract that is accepted but not yet dispatched ('pending')
|
||||
// or already flying ('inflight' — planeId set and that plane's status is 'flying').
|
||||
// Open/completed/expired contracts draw nothing.
|
||||
// One LineString per FLYING plane — its current leg from locationIcao to dest_icao.
|
||||
// Grounded planes draw nothing; a flying plane missing either endpoint from the
|
||||
// dataset is skipped, never guessed.
|
||||
export function routesGeoJson(
|
||||
state: StateSnapshot | null,
|
||||
airportsByIcao: ReadonlyMap<string, AirportCoord>,
|
||||
): FeatureCollection<MapLineFeature> {
|
||||
if (!state) return EMPTY_LINES;
|
||||
const planeById = new Map(state.planes.map((p) => [p.id, p]));
|
||||
const features: MapLineFeature[] = [];
|
||||
for (const c of state.contracts) {
|
||||
if (c.status !== 'accepted') continue;
|
||||
const from = airportsByIcao.get(c.originIcao);
|
||||
const to = airportsByIcao.get(c.destIcao);
|
||||
for (const p of state.planes) {
|
||||
if (p.status !== 'flying' || !p.destIcao) continue;
|
||||
const from = airportsByIcao.get(p.locationIcao);
|
||||
const to = airportsByIcao.get(p.destIcao);
|
||||
if (!from || !to) continue; // endpoint missing from the dataset — skip, don't guess
|
||||
const plane = c.planeId ? planeById.get(c.planeId) : undefined;
|
||||
features.push({
|
||||
type: 'Feature',
|
||||
geometry: {
|
||||
@@ -94,7 +90,7 @@ export function routesGeoJson(
|
||||
[to.lon, to.lat],
|
||||
],
|
||||
},
|
||||
properties: { contractId: c.id, kind: plane?.status === 'flying' ? 'inflight' : 'pending' },
|
||||
properties: { planeId: p.id },
|
||||
});
|
||||
}
|
||||
return { type: 'FeatureCollection', features };
|
||||
|
||||
+39
-27
@@ -3,13 +3,14 @@ import { describe, expect, it } from 'vitest';
|
||||
import { openApiSpec } from './openapi';
|
||||
|
||||
describe('OpenAPI spec', () => {
|
||||
it('documents exactly the nine public endpoints (4 read + 5 player actions)', () => {
|
||||
it('documents exactly the ten public endpoints (4 read + 6 player actions)', () => {
|
||||
expect(Object.keys(openApiSpec.paths).sort()).toEqual([
|
||||
'/api/airports',
|
||||
'/api/contracts/{id}/accept',
|
||||
'/api/market/buy-plane',
|
||||
'/api/market/sell-plane',
|
||||
'/api/planes/{planeId}/dispatch',
|
||||
'/api/packages/{id}/abandon',
|
||||
'/api/packages/{id}/load',
|
||||
'/api/planes/{planeId}/fly',
|
||||
'/api/planes/{planeId}/refuel',
|
||||
'/api/sim',
|
||||
'/api/state',
|
||||
@@ -57,7 +58,7 @@ describe('OpenAPI spec', () => {
|
||||
expect(props.version.type).toBe('string');
|
||||
});
|
||||
|
||||
it('describes /api/state as a StateSnapshot with account, simState, planes and contracts', () => {
|
||||
it('describes /api/state as a StateSnapshot with account, simState, planes and packages', () => {
|
||||
const schema = openApiSpec.paths['/api/state'].get.responses[200].content['application/json'].schema;
|
||||
expect(schema.$ref).toBe('#/components/schemas/StateSnapshot');
|
||||
|
||||
@@ -65,8 +66,8 @@ describe('OpenAPI spec', () => {
|
||||
expect(Object.keys(snap).sort()).toEqual([
|
||||
'account',
|
||||
'catalog',
|
||||
'contracts',
|
||||
'fuelPricePerL',
|
||||
'packages',
|
||||
'planes',
|
||||
'sellFraction',
|
||||
'simState',
|
||||
@@ -74,8 +75,8 @@ describe('OpenAPI spec', () => {
|
||||
expect(openApiSpec.components.schemas.StateSnapshot.required.sort()).toEqual([
|
||||
'account',
|
||||
'catalog',
|
||||
'contracts',
|
||||
'fuelPricePerL',
|
||||
'packages',
|
||||
'planes',
|
||||
'sellFraction',
|
||||
'simState',
|
||||
@@ -83,23 +84,25 @@ describe('OpenAPI spec', () => {
|
||||
expect(snap.account.$ref).toBe('#/components/schemas/AccountState');
|
||||
expect(snap.simState.$ref).toBe('#/components/schemas/SimState');
|
||||
expect(snap.planes.items.$ref).toBe('#/components/schemas/PlaneState');
|
||||
expect(snap.contracts.items.$ref).toBe('#/components/schemas/ContractState');
|
||||
expect(snap.packages.items.$ref).toBe('#/components/schemas/PackageState');
|
||||
expect(snap.catalog.items.$ref).toBe('#/components/schemas/CatalogEntry');
|
||||
expect(snap.fuelPricePerL.type).toBe('number');
|
||||
expect(snap.sellFraction.type).toBe('number');
|
||||
|
||||
const catalog = openApiSpec.components.schemas.CatalogEntry.properties;
|
||||
expect(Object.keys(catalog).sort()).toEqual(['burnPerKm', 'label', 'maxFuel', 'model', 'price', 'speedKmh']);
|
||||
expect(Object.keys(catalog).sort()).toEqual(['burnPerKm', 'capacity', 'label', 'maxFuel', 'model', 'price', 'speedKmh']);
|
||||
for (const key of ['burnPerKm', 'maxFuel', 'price', 'speedKmh'] as const) {
|
||||
expect(catalog[key].type, `CatalogEntry.${key}`).toBe('number');
|
||||
}
|
||||
expect(catalog.capacity.type).toBe('integer'); // v0.12.0 slot capacity
|
||||
expect(catalog.model.type).toBe('string');
|
||||
expect(catalog.label.type).toBe('string');
|
||||
|
||||
const plane = openApiSpec.components.schemas.PlaneState.properties;
|
||||
expect(Object.keys(plane).sort()).toEqual([
|
||||
'contractId',
|
||||
'departureSimTime',
|
||||
'destIcao',
|
||||
'destName',
|
||||
'fuel',
|
||||
'id',
|
||||
'lat',
|
||||
@@ -111,8 +114,8 @@ describe('OpenAPI spec', () => {
|
||||
'status',
|
||||
]);
|
||||
|
||||
const contract = openApiSpec.components.schemas.ContractState.properties;
|
||||
expect(Object.keys(contract).sort()).toEqual([
|
||||
const pkg = openApiSpec.components.schemas.PackageState.properties;
|
||||
expect(Object.keys(pkg).sort()).toEqual([
|
||||
'cargoCount',
|
||||
'cargoType',
|
||||
'createdSimTime',
|
||||
@@ -130,8 +133,8 @@ describe('OpenAPI spec', () => {
|
||||
const sim = openApiSpec.components.schemas.SimState.properties;
|
||||
expect(Object.keys(sim).sort()).toEqual(['clockMs', 'paused', 'timeScale']);
|
||||
|
||||
const contractStatus = openApiSpec.components.schemas.ContractState.properties.status;
|
||||
expect(contractStatus.enum.sort()).toEqual(['accepted', 'completed', 'expired', 'open']);
|
||||
const packageStatus = openApiSpec.components.schemas.PackageState.properties.status;
|
||||
expect(packageStatus.enum.sort()).toEqual(['abandoned', 'delivered', 'expired', 'loaded', 'open']);
|
||||
});
|
||||
|
||||
it('describes POST /api/sim as SimControlsRequest → SimState with a 400 error shape', () => {
|
||||
@@ -157,7 +160,7 @@ describe('OpenAPI spec', () => {
|
||||
expect(Object.keys(error)).toEqual(['error']);
|
||||
});
|
||||
|
||||
it('documents the five action endpoints: snapshot on 200, Error on their 4xx paths', () => {
|
||||
it('documents the six action endpoints: snapshot on 200, Error on their 4xx paths', () => {
|
||||
// The spec object is a literal type; these helpers view it as plain JSON.
|
||||
const post = (p: string) =>
|
||||
((openApiSpec.paths as Record<string, { post?: unknown }>)[p]?.post ?? {}) as {
|
||||
@@ -168,8 +171,9 @@ describe('OpenAPI spec', () => {
|
||||
|
||||
// Every action returns the full StateSnapshot on success (response convention).
|
||||
for (const p of [
|
||||
'/api/contracts/{id}/accept',
|
||||
'/api/planes/{planeId}/dispatch',
|
||||
'/api/packages/{id}/load',
|
||||
'/api/packages/{id}/abandon',
|
||||
'/api/planes/{planeId}/fly',
|
||||
'/api/market/buy-plane',
|
||||
'/api/market/sell-plane',
|
||||
'/api/planes/{planeId}/refuel',
|
||||
@@ -180,15 +184,19 @@ describe('OpenAPI spec', () => {
|
||||
|
||||
// Error shapes per endpoint.
|
||||
const errorCodes = (p: string) => Object.keys(post(p).responses).filter((k) => k !== '200').sort();
|
||||
expect(errorCodes('/api/contracts/{id}/accept')).toEqual(['404', '409']);
|
||||
expect(errorCodes('/api/planes/{planeId}/dispatch')).toEqual(['400', '404', '409']);
|
||||
expect(errorCodes('/api/packages/{id}/load')).toEqual(['400', '404', '409']);
|
||||
expect(errorCodes('/api/packages/{id}/abandon')).toEqual(['404', '409']);
|
||||
expect(errorCodes('/api/planes/{planeId}/fly')).toEqual(['400', '404', '409']);
|
||||
expect(errorCodes('/api/market/buy-plane')).toEqual(['400', '409']);
|
||||
expect(errorCodes('/api/market/sell-plane')).toEqual(['400', '404', '409']);
|
||||
expect(errorCodes('/api/planes/{planeId}/refuel')).toEqual(['404', '409']);
|
||||
|
||||
// Request bodies: dispatch/buy/sell take their dedicated schemas; accept/refuel take none.
|
||||
expect(post('/api/planes/{planeId}/dispatch').requestBody?.content['application/json'].schema.$ref).toBe(
|
||||
'#/components/schemas/DispatchRequest',
|
||||
// Request bodies: load/fly/buy/sell take their dedicated schemas; abandon/refuel take none.
|
||||
expect(post('/api/packages/{id}/load').requestBody?.content['application/json'].schema.$ref).toBe(
|
||||
'#/components/schemas/LoadPackageRequest',
|
||||
);
|
||||
expect(post('/api/planes/{planeId}/fly').requestBody?.content['application/json'].schema.$ref).toBe(
|
||||
'#/components/schemas/FlyPlaneRequest',
|
||||
);
|
||||
expect(post('/api/market/buy-plane').requestBody?.content['application/json'].schema.$ref).toBe(
|
||||
'#/components/schemas/BuyPlaneRequest',
|
||||
@@ -196,19 +204,23 @@ describe('OpenAPI spec', () => {
|
||||
expect(post('/api/market/sell-plane').requestBody?.content['application/json'].schema.$ref).toBe(
|
||||
'#/components/schemas/SellPlaneRequest',
|
||||
);
|
||||
expect(post('/api/contracts/{id}/accept').requestBody).toBeUndefined();
|
||||
expect(post('/api/packages/{id}/abandon').requestBody).toBeUndefined();
|
||||
expect(post('/api/planes/{planeId}/refuel').requestBody).toBeUndefined();
|
||||
|
||||
// Path parameters are declared on the parameterized routes.
|
||||
const paramNames = (p: string) => post(p).parameters?.map((x) => x.name);
|
||||
expect(paramNames('/api/contracts/{id}/accept')).toEqual(['id']);
|
||||
expect(paramNames('/api/planes/{planeId}/dispatch')).toEqual(['planeId']);
|
||||
expect(paramNames('/api/packages/{id}/load')).toEqual(['id']);
|
||||
expect(paramNames('/api/packages/{id}/abandon')).toEqual(['id']);
|
||||
expect(paramNames('/api/planes/{planeId}/fly')).toEqual(['planeId']);
|
||||
expect(paramNames('/api/planes/{planeId}/refuel')).toEqual(['planeId']);
|
||||
|
||||
// Request schema shapes.
|
||||
const dispatch = openApiSpec.components.schemas.DispatchRequest;
|
||||
expect(dispatch.required).toEqual(['contractId']);
|
||||
expect(dispatch.properties.contractId.type).toBe('string');
|
||||
const load = openApiSpec.components.schemas.LoadPackageRequest;
|
||||
expect(load.required).toEqual(['planeId']);
|
||||
expect(load.properties.planeId.type).toBe('string');
|
||||
const fly = openApiSpec.components.schemas.FlyPlaneRequest;
|
||||
expect(fly.required).toEqual(['destIcao']);
|
||||
expect(fly.properties.destIcao.type).toBe('string');
|
||||
const buy = openApiSpec.components.schemas.BuyPlaneRequest;
|
||||
expect(buy.required).toEqual(['model']);
|
||||
expect(buy.properties.model.type).toBe('string');
|
||||
|
||||
+89
-34
@@ -8,7 +8,7 @@ export const openApiSpec = {
|
||||
info: {
|
||||
title: 'Flight Ops API',
|
||||
description:
|
||||
'JSON API for Flight Ops — EU airport data for the map, the live game-state snapshot, player actions (accept / dispatch / 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 / refuel), 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.
|
||||
version: pkg.version,
|
||||
},
|
||||
@@ -37,7 +37,7 @@ export const openApiSpec = {
|
||||
get: {
|
||||
summary: 'Game state snapshot',
|
||||
description:
|
||||
'Full current game state for client polling — account, sim clock, planes and contracts, 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/finalization/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/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.',
|
||||
operationId: 'getState',
|
||||
responses: {
|
||||
200: {
|
||||
@@ -55,7 +55,7 @@ export const openApiSpec = {
|
||||
post: {
|
||||
summary: 'Set sim time controls',
|
||||
description:
|
||||
'Advance the sim clock (tick-on-read) and set the time scale / pause state. The clock is advanced first, so the returned simState already reflects current game time; contract expiry, arrival finalization and market spawn run inside that tick.',
|
||||
'Advance the sim clock (tick-on-read) and set the time scale / pause state. The clock is advanced first, so the returned simState already reflects current game time; package expiry, arrival delivery and market spawn run inside that tick.',
|
||||
operationId: 'setSimControls',
|
||||
requestBody: {
|
||||
required: false,
|
||||
@@ -102,37 +102,75 @@ export const openApiSpec = {
|
||||
},
|
||||
},
|
||||
},
|
||||
'/api/contracts/{id}/accept': {
|
||||
'/api/packages/{id}/load': {
|
||||
post: {
|
||||
summary: 'Accept a contract',
|
||||
summary: 'Load a package onto a plane',
|
||||
description:
|
||||
'Claim an open contract: status flips open → accepted (v0.8.0). The sim clock is ticked first, so the returned snapshot reflects current game time. No body.',
|
||||
operationId: 'acceptContract',
|
||||
'Bind an OPEN package to a GROUNDED ("available") plane at the package\'s origin (v0.12.0). The plane needs a free slot — capacity per catalog model; expired packages still occupy theirs. The sim clock is ticked first, so the returned snapshot reflects current game time.',
|
||||
operationId: 'loadPackage',
|
||||
parameters: [
|
||||
{ name: 'id', in: 'path', required: true, schema: { type: 'string' } },
|
||||
],
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: { $ref: '#/components/schemas/LoadPackageRequest' },
|
||||
},
|
||||
},
|
||||
},
|
||||
responses: {
|
||||
200: {
|
||||
description: 'Accepted — full state snapshot (contract now "accepted")',
|
||||
description: 'Loaded — full state snapshot (package now "loaded" on that plane)',
|
||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/StateSnapshot' } } },
|
||||
},
|
||||
400: {
|
||||
description: 'Invalid body (not an object, unknown field, or missing/non-string planeId)',
|
||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||
},
|
||||
404: {
|
||||
description: 'Unknown contract id',
|
||||
description: 'Unknown package id or plane id',
|
||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||
},
|
||||
409: {
|
||||
description: 'Contract is not "open" (accepted / completed / expired)',
|
||||
description:
|
||||
'Package not "open", plane not grounded, plane not at the origin, or no free slot on the plane',
|
||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
'/api/planes/{planeId}/dispatch': {
|
||||
'/api/packages/{id}/abandon': {
|
||||
post: {
|
||||
summary: 'Dispatch a plane on an accepted contract',
|
||||
summary: 'Abandon a loaded package',
|
||||
description:
|
||||
'Bind an ACCEPTED contract to a grounded plane at its origin (v0.8.0). The plane becomes "flying" with departureSimTime = current sim clock; the engine then flies it analytically and pays out reward + reputation on arrival. Validation: contract must be "accepted", plane "available" and located at the contract origin, with enough fuel for the leg (burnPerKm × great-circle km).',
|
||||
operationId: 'dispatchPlane',
|
||||
'Drop a LOADED (or already EXPIRED) package while its plane is GROUNDED (v0.12.0). Penalty = fraction of the payout scaling with time pressure — 15% at creation up to 60% at the deadline; expired packages cost nothing and cash floors at €0. The slot is freed immediately. No body.',
|
||||
operationId: 'abandonPackage',
|
||||
parameters: [
|
||||
{ name: 'id', in: 'path', required: true, schema: { type: 'string' } },
|
||||
],
|
||||
responses: {
|
||||
200: {
|
||||
description: 'Abandoned — full state snapshot (package "abandoned", cash reduced by the penalty)',
|
||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/StateSnapshot' } } },
|
||||
},
|
||||
404: {
|
||||
description: 'Unknown package id',
|
||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||
},
|
||||
409: {
|
||||
description: 'Package not "loaded"/"expired", or its plane is in flight',
|
||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
'/api/planes/{planeId}/fly': {
|
||||
post: {
|
||||
summary: 'Fly a plane to an airport',
|
||||
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.',
|
||||
operationId: 'flyPlane',
|
||||
parameters: [
|
||||
{ name: 'planeId', in: 'path', required: true, schema: { type: 'string' } },
|
||||
],
|
||||
@@ -140,26 +178,26 @@ export const openApiSpec = {
|
||||
required: true,
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: { $ref: '#/components/schemas/DispatchRequest' },
|
||||
schema: { $ref: '#/components/schemas/FlyPlaneRequest' },
|
||||
},
|
||||
},
|
||||
},
|
||||
responses: {
|
||||
200: {
|
||||
description: 'Dispatched — full state snapshot (plane "flying", departure set)',
|
||||
description: 'Flying — full state snapshot (plane "flying", departure + destination set)',
|
||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/StateSnapshot' } } },
|
||||
},
|
||||
400: {
|
||||
description: 'Invalid body (not an object, unknown field, or missing/non-string contractId)',
|
||||
description:
|
||||
'Invalid body (not an object, unknown field, or missing/non-string destIcao) or the ICAO is not in the airport dataset',
|
||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||
},
|
||||
404: {
|
||||
description: 'Unknown plane id or contract id',
|
||||
description: 'Unknown plane id',
|
||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||
},
|
||||
409: {
|
||||
description:
|
||||
'Contract not "accepted", plane not "available", plane not at the origin, or insufficient fuel for the leg',
|
||||
description: 'Plane not grounded, or insufficient fuel for the leg (burnPerKm × great-circle km)',
|
||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||
},
|
||||
},
|
||||
@@ -317,9 +355,9 @@ export const openApiSpec = {
|
||||
type: 'array',
|
||||
items: { $ref: '#/components/schemas/PlaneState' },
|
||||
},
|
||||
contracts: {
|
||||
packages: {
|
||||
type: 'array',
|
||||
items: { $ref: '#/components/schemas/ContractState' },
|
||||
items: { $ref: '#/components/schemas/PackageState' },
|
||||
},
|
||||
catalog: {
|
||||
type: 'array',
|
||||
@@ -329,19 +367,20 @@ export const openApiSpec = {
|
||||
fuelPricePerL: { type: 'number', description: 'Jet-A1 price in €/liter; refuel cost = (maxFuel − fuel) × this.' },
|
||||
sellFraction: { type: 'number', description: 'Fraction of the catalog price paid out when selling a plane.' },
|
||||
},
|
||||
required: ['account', 'simState', 'planes', 'contracts', 'catalog', 'fuelPricePerL', 'sellFraction'],
|
||||
required: ['account', 'simState', 'planes', 'packages', 'catalog', 'fuelPricePerL', 'sellFraction'],
|
||||
},
|
||||
CatalogEntry: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
model: { type: 'string', description: 'Catalog model id (e.g. "atr72") — used by buy/dispatch.' },
|
||||
model: { type: 'string', description: 'Catalog model id (e.g. "atr72") — used by buy/fly.' },
|
||||
label: { type: 'string', description: 'Display name (e.g. "ATR 72-600").' },
|
||||
price: { type: 'number', description: 'Market price in € (buy cost; sell pays out sellFraction × this).' },
|
||||
maxFuel: { type: 'number', description: 'Fuel capacity, liters.' },
|
||||
burnPerKm: { type: 'number', description: 'Cruise fuel burn, liters/km.' },
|
||||
speedKmh: { type: 'number', description: 'Cruise speed, km/h.' },
|
||||
capacity: { type: 'integer', description: 'Cargo slot capacity — packages that can be loaded on one plane (v0.12.0).' },
|
||||
},
|
||||
required: ['model', 'label', 'price', 'maxFuel', 'burnPerKm', 'speedKmh'],
|
||||
required: ['model', 'label', 'price', 'maxFuel', 'burnPerKm', 'speedKmh', 'capacity'],
|
||||
},
|
||||
AccountState: {
|
||||
type: 'object',
|
||||
@@ -373,12 +412,19 @@ export const openApiSpec = {
|
||||
paused: { type: 'boolean' },
|
||||
},
|
||||
},
|
||||
DispatchRequest: {
|
||||
LoadPackageRequest: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
contractId: { type: 'string', description: 'An ACCEPTED contract whose origin the plane is at.' },
|
||||
planeId: { type: 'string', description: 'A GROUNDED ("available") plane at the package\'s origin with a free slot.' },
|
||||
},
|
||||
required: ['contractId'],
|
||||
required: ['planeId'],
|
||||
},
|
||||
FlyPlaneRequest: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
destIcao: { type: 'string', description: 'Any airport ICAO from the dataset — a loaded package\'s destination or repositioning.' },
|
||||
},
|
||||
required: ['destIcao'],
|
||||
},
|
||||
BuyPlaneRequest: {
|
||||
type: 'object',
|
||||
@@ -411,10 +457,17 @@ export const openApiSpec = {
|
||||
maxFuel: { type: 'number' },
|
||||
locationIcao: { type: 'string' },
|
||||
locationName: { type: 'string' },
|
||||
contractId: { type: ['string', 'null'] },
|
||||
destIcao: {
|
||||
type: ['string', 'null'],
|
||||
description: 'Current flight destination (set by fly, cleared on arrival); null when grounded.',
|
||||
},
|
||||
destName: {
|
||||
type: ['string', 'null'],
|
||||
description: 'Display name of destIcao; null when grounded.',
|
||||
},
|
||||
departureSimTime: {
|
||||
type: ['integer', 'null'],
|
||||
description: 'Sim-clock epoch ms of the current flight (set by dispatch); null when grounded.',
|
||||
description: 'Sim-clock epoch ms of the current flight (set by fly); null when grounded.',
|
||||
},
|
||||
lat: { type: 'number' },
|
||||
lon: { type: 'number' },
|
||||
@@ -427,13 +480,14 @@ export const openApiSpec = {
|
||||
'maxFuel',
|
||||
'locationIcao',
|
||||
'locationName',
|
||||
'contractId',
|
||||
'destIcao',
|
||||
'destName',
|
||||
'departureSimTime',
|
||||
'lat',
|
||||
'lon',
|
||||
],
|
||||
},
|
||||
ContractState: {
|
||||
PackageState: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: { type: 'string' },
|
||||
@@ -445,8 +499,9 @@ export const openApiSpec = {
|
||||
cargoType: { type: 'string' },
|
||||
cargoCount: { type: 'integer' },
|
||||
deadlineSimTime: { type: 'integer', description: 'Sim-clock epoch ms (game time)' },
|
||||
// 'expired' = an open contract whose deadline passed; accepted/in-flight contracts never expire.
|
||||
status: { enum: ['open', 'accepted', 'completed', 'expired'] },
|
||||
// 'expired' = an open OR loaded package whose deadline passed on a tick;
|
||||
// loaded expired packages keep their slot, deliver no reward, abandon free.
|
||||
status: { enum: ['open', 'loaded', 'delivered', 'expired', 'abandoned'] },
|
||||
planeId: { type: ['string', 'null'] },
|
||||
createdSimTime: { type: 'integer' },
|
||||
},
|
||||
|
||||
+135
-102
@@ -8,15 +8,15 @@ import * as schema from '@/lib/db/schema';
|
||||
import { loadAirportsGeoJson } from '@/lib/airports';
|
||||
import { haversineKm } from '@/lib/geo';
|
||||
import { PLANE_TYPES } from '@/lib/game/catalog';
|
||||
import { MARKET_TARGET_OPEN_CONTRACTS, mulberry32 } from '@/lib/game/seed';
|
||||
import { MARKET_TARGET_OPEN_PACKAGES, mulberry32 } from '@/lib/game/seed';
|
||||
import { arrivalTimeFor } from './movement';
|
||||
import {
|
||||
expireContracts,
|
||||
finalizeArrivals,
|
||||
deliverPackages,
|
||||
expirePackages,
|
||||
MAX_TICK_ELAPSED_MS,
|
||||
reputationGainFor,
|
||||
spawnCoverageContracts,
|
||||
spawnOpenContracts,
|
||||
spawnCoveragePackages,
|
||||
spawnOpenPackages,
|
||||
tickOnce,
|
||||
} from './engine';
|
||||
|
||||
@@ -91,37 +91,41 @@ describe('tickOnce — clock advance', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('expireContracts', () => {
|
||||
it('flips only open contracts past their deadline; accepted ones never expire', async () => {
|
||||
describe('expirePackages', () => {
|
||||
it('flips open AND loaded packages past their deadline; terminal statuses never expire', async () => {
|
||||
const inst = await freshDb('expiry.db');
|
||||
const clock = T0 + 100_000;
|
||||
|
||||
await inst.db.insert(schema.contracts).values([
|
||||
{ id: 'c-open-past', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: clock - 1, status: 'open', planeId: null, createdSimTime: T0 },
|
||||
{ id: 'c-open-future', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: clock + 1, status: 'open', planeId: null, createdSimTime: T0 },
|
||||
{ id: 'c-accepted-past', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: clock - 1, status: 'accepted', planeId: null, createdSimTime: T0 },
|
||||
await inst.db.insert(schema.packages).values([
|
||||
{ id: 'p-open-past', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: clock - 1, status: 'open', planeId: null, createdSimTime: T0 },
|
||||
{ id: 'p-open-future', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: clock + 1, status: 'open', planeId: null, createdSimTime: T0 },
|
||||
{ id: 'p-loaded-past', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: clock - 1, status: 'loaded', planeId: 'plane-starter', createdSimTime: T0 },
|
||||
{ id: 'p-delivered-past', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: clock - 1, status: 'delivered', planeId: null, createdSimTime: T0 },
|
||||
{ id: 'p-abandoned-past', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: clock - 1, status: 'abandoned', planeId: null, createdSimTime: T0 },
|
||||
]);
|
||||
|
||||
const n = await expireContracts(inst, clock);
|
||||
expect(n).toBe(1);
|
||||
const n = await expirePackages(inst, clock);
|
||||
expect(n).toBe(2); // the open and the loaded one
|
||||
|
||||
const byId = new Map((await inst.db.select().from(schema.contracts)).map((c) => [c.id, c.status]));
|
||||
expect(byId.get('c-open-past')).toBe('expired');
|
||||
expect(byId.get('c-open-future')).toBe('open'); // deadline not reached yet
|
||||
expect(byId.get('c-accepted-past')).toBe('accepted'); // accepted contracts complete, never expire
|
||||
const byId = new Map((await inst.db.select().from(schema.packages)).map((p) => [p.id, p.status]));
|
||||
expect(byId.get('p-open-past')).toBe('expired');
|
||||
expect(byId.get('p-open-future')).toBe('open'); // deadline not reached yet
|
||||
expect(byId.get('p-loaded-past')).toBe('expired'); // v0.12.0: loaded packages expire too (keep their slot)
|
||||
expect(byId.get('p-delivered-past')).toBe('delivered'); // terminal — never flips
|
||||
expect(byId.get('p-abandoned-past')).toBe('abandoned'); // terminal — never flips
|
||||
});
|
||||
|
||||
it('a deadline exactly at the clock counts as expired', async () => {
|
||||
const inst = await freshDb('expiry-edge.db');
|
||||
await inst.db.insert(schema.contracts).values({
|
||||
id: 'c-edge', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1,
|
||||
await inst.db.insert(schema.packages).values({
|
||||
id: 'p-edge', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1,
|
||||
deadlineSimTime: T0 + 50_000, status: 'open', planeId: null, createdSimTime: T0,
|
||||
});
|
||||
expect(await expireContracts(inst, T0 + 50_000)).toBe(1); // <= is inclusive
|
||||
expect(await expirePackages(inst, T0 + 50_000)).toBe(1); // <= is inclusive
|
||||
});
|
||||
});
|
||||
|
||||
describe('finalizeArrivals', () => {
|
||||
describe('deliverPackages (v0.12.0 arrival delivery)', () => {
|
||||
const FROM = 'EDDF';
|
||||
const TO = 'LEMD';
|
||||
|
||||
@@ -133,25 +137,21 @@ describe('finalizeArrivals', () => {
|
||||
const km = haversineKm(from.lat, from.lon, to.lat, to.lon);
|
||||
const type = PLANE_TYPES.atr72;
|
||||
|
||||
// A dispatched flight: contract accepted + bound to the plane, plane flying
|
||||
// with its fuel frozen at departure (the v0.8.0 dispatch step writes these).
|
||||
await inst.db.insert(schema.contracts).values({
|
||||
id: 'c-flight', originIcao: FROM, destIcao: TO, reward: 5_000, cargoType: 'Passengers',
|
||||
cargoCount: 60, deadlineSimTime: T0 + 24 * 3_600_000, status: 'accepted', planeId: 'plane-starter', createdSimTime: T0,
|
||||
});
|
||||
// A manual flight (v0.12.0 fly): plane flying with dest_icao set and its fuel
|
||||
// frozen at departure — no contract involved anymore.
|
||||
await inst.db.update(schema.planes)
|
||||
.set({ status: 'flying', contractId: 'c-flight', departureSimTime: T0, fuel: type.maxFuel })
|
||||
.set({ status: 'flying', destIcao: TO, departureSimTime: T0, fuel: type.maxFuel })
|
||||
.where(eq(schema.planes.id, 'plane-starter'));
|
||||
|
||||
return { inst, from, to, km, type };
|
||||
}
|
||||
|
||||
it('does nothing before the arrival time', async () => {
|
||||
const { inst, km, type } = await setupFlight('finalize-early.db');
|
||||
const { inst, km, type } = await setupFlight('deliver-early.db');
|
||||
const accountBefore = (await inst.db.select().from(schema.account))[0]!;
|
||||
|
||||
const clock = T0 + travelMs(km, type.speedKmh) - 1; // one ms before arrival
|
||||
expect(await finalizeArrivals(inst, clock)).toBe(0);
|
||||
expect(await deliverPackages(inst, clock)).toBe(0);
|
||||
|
||||
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||
const account = (await inst.db.select().from(schema.account))[0]!;
|
||||
@@ -159,12 +159,20 @@ describe('finalizeArrivals', () => {
|
||||
expect(account.cash).toBe(accountBefore.cash); // no award before landing
|
||||
});
|
||||
|
||||
it('awards cash + reputation exactly once and grounds the plane at the destination', async () => {
|
||||
const { inst, to, km, type } = await setupFlight('finalize-late.db');
|
||||
it('delivers in-deadline cargo, unbinds expired cargo for free, keeps other-dest cargo bound', async () => {
|
||||
const { inst, to, km, type } = await setupFlight('deliver-mixed.db');
|
||||
const accountBefore = (await inst.db.select().from(schema.account))[0]!;
|
||||
|
||||
// Three packages on the plane: one in-deadline for TO, one expired for TO,
|
||||
// one loaded for a DIFFERENT airport (stays bound for a later leg).
|
||||
await inst.db.insert(schema.packages).values([
|
||||
{ id: 'p-pay', originIcao: FROM, destIcao: TO, reward: 5_000, cargoType: 'Passengers', cargoCount: 60, deadlineSimTime: T0 + 24 * 3_600_000, status: 'loaded', planeId: 'plane-starter', createdSimTime: T0 },
|
||||
{ id: 'p-late', originIcao: FROM, destIcao: TO, reward: 7_000, cargoType: 'Mail', cargoCount: 10, deadlineSimTime: T0 + 3_600_000, status: 'expired', planeId: 'plane-starter', createdSimTime: T0 },
|
||||
{ id: 'p-elsewhere', originIcao: FROM, destIcao: 'EHAM', reward: 9_000, cargoType: 'Mail', cargoCount: 10, deadlineSimTime: T0 + 24 * 3_600_000, status: 'loaded', planeId: 'plane-starter', createdSimTime: T0 },
|
||||
]);
|
||||
|
||||
const clock = T0 + travelMs(km, type.speedKmh); // exactly at arrival
|
||||
expect(await finalizeArrivals(inst, clock)).toBe(1);
|
||||
expect(await deliverPackages(inst, clock)).toBe(1);
|
||||
|
||||
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||
expect(plane.status).toBe('available');
|
||||
@@ -173,65 +181,90 @@ describe('finalizeArrivals', () => {
|
||||
expect(plane.lon).toBe(to.lon);
|
||||
expect(plane.fuel).toBeCloseTo(Math.max(0, type.maxFuel - type.burnPerKm * km), 6); // remaining fuel
|
||||
expect(plane.departureSimTime).toBeNull();
|
||||
expect(plane.destIcao).toBeNull(); // flight context cleared on landing
|
||||
|
||||
const contract = (await inst.db.select().from(schema.contracts)).find((c) => c.id === 'c-flight')!;
|
||||
expect(contract.status).toBe('completed');
|
||||
const byId = new Map((await inst.db.select().from(schema.packages)).map((p) => [p.id, p]));
|
||||
expect(byId.get('p-pay')!.status).toBe('delivered');
|
||||
expect(byId.get('p-late')!.status).toBe('expired'); // still expired — just unbound…
|
||||
expect(byId.get('p-late')!.planeId).toBeNull(); // …slot freed, no reward
|
||||
expect(byId.get('p-elsewhere')!.status).toBe('loaded'); // not this airport's cargo…
|
||||
expect(byId.get('p-elsewhere')!.planeId).toBe('plane-starter'); // …stays bound for the next leg
|
||||
|
||||
const account = (await inst.db.select().from(schema.account))[0]!;
|
||||
expect(account.cash).toBeCloseTo(accountBefore.cash + 5_000, 9); // exact reward
|
||||
expect(account.cash).toBeCloseTo(accountBefore.cash + 5_000, 9); // ONLY p-pay paid out
|
||||
expect(account.reputation).toBeCloseTo(
|
||||
Math.round((accountBefore.reputation + reputationGainFor(km)) * 100) / 100,
|
||||
9,
|
||||
);
|
||||
|
||||
// A later tick must not award again — the plane is no longer 'flying'.
|
||||
expect(await finalizeArrivals(inst, clock + 3_600_000)).toBe(0);
|
||||
expect(await deliverPackages(inst, clock + 3_600_000)).toBe(0);
|
||||
const accountAfter = (await inst.db.select().from(schema.account))[0]!;
|
||||
expect(accountAfter.cash).toBe(account.cash);
|
||||
expect(accountAfter.reputation).toBe(account.reputation);
|
||||
});
|
||||
|
||||
it('delivers every in-deadline package for the arrival airport with per-package rewards', async () => {
|
||||
const { inst, km } = await setupFlight('deliver-multi.db');
|
||||
const accountBefore = (await inst.db.select().from(schema.account))[0]!;
|
||||
|
||||
await inst.db.insert(schema.packages).values([
|
||||
{ id: 'p-a', originIcao: FROM, destIcao: TO, reward: 1_000, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: T0 + 24 * 3_600_000, status: 'loaded', planeId: 'plane-starter', createdSimTime: T0 },
|
||||
{ id: 'p-b', originIcao: FROM, destIcao: TO, reward: 2_500, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: T0 + 24 * 3_600_000, status: 'loaded', planeId: 'plane-starter', createdSimTime: T0 },
|
||||
]);
|
||||
|
||||
const clock = T0 + travelMs(km, PLANE_TYPES.atr72.speedKmh);
|
||||
expect(await deliverPackages(inst, clock)).toBe(1);
|
||||
|
||||
const account = (await inst.db.select().from(schema.account))[0]!;
|
||||
expect(account.cash).toBeCloseTo(accountBefore.cash + 3_500, 9); // both rewards
|
||||
expect(account.reputation).toBeCloseTo(
|
||||
Math.round((accountBefore.reputation + reputationGainFor(km) * 2) * 100) / 100,
|
||||
9,
|
||||
); // rep per delivered package
|
||||
});
|
||||
|
||||
it('leaves planes without route info alone', async () => {
|
||||
const inst = await freshDb('finalize-noroute.db');
|
||||
// Flying plane whose contract row is missing — defensive skip, no crash.
|
||||
const inst = await freshDb('deliver-noroute.db');
|
||||
// Flying plane whose dest_icao is missing — defensive skip, no crash.
|
||||
await inst.db.update(schema.planes)
|
||||
.set({ status: 'flying', departureSimTime: T0, contractId: 'c-missing' });
|
||||
expect(await finalizeArrivals(inst, T0 + 3_600_000)).toBe(0);
|
||||
.set({ status: 'flying', departureSimTime: T0 });
|
||||
expect(await deliverPackages(inst, T0 + 3_600_000)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('spawnOpenContracts', () => {
|
||||
it('tops the market up to MARKET_TARGET_OPEN_CONTRACTS using the shared seed builder', async () => {
|
||||
describe('spawnOpenPackages', () => {
|
||||
it('tops the market up to MARKET_TARGET_OPEN_PACKAGES using the shared seed builder', async () => {
|
||||
const inst = await freshDb('spawn.db');
|
||||
const clock = T0 + 123_456;
|
||||
|
||||
// Leave exactly 3 open contracts (the rest of the seeded set is "done").
|
||||
const all = await inst.db.select().from(schema.contracts);
|
||||
for (const c of all.slice(3)) {
|
||||
await inst.db.update(schema.contracts).set({ status: 'completed' }).where(eq(schema.contracts.id, c.id));
|
||||
// Leave exactly 3 open packages (the rest of the seeded set is "done").
|
||||
const all = await inst.db.select().from(schema.packages);
|
||||
for (const p of all.slice(3)) {
|
||||
await inst.db.update(schema.packages).set({ status: 'delivered' }).where(eq(schema.packages.id, p.id));
|
||||
}
|
||||
|
||||
const needed = await spawnOpenContracts(inst, clock, mulberry32(7));
|
||||
expect(needed).toBe(MARKET_TARGET_OPEN_CONTRACTS - 3);
|
||||
const needed = await spawnOpenPackages(inst, clock, mulberry32(7));
|
||||
expect(needed).toBe(MARKET_TARGET_OPEN_PACKAGES - 3);
|
||||
|
||||
const openRows = (await inst.db.select().from(schema.contracts)).filter((c) => c.status === 'open');
|
||||
expect(openRows.length).toBe(MARKET_TARGET_OPEN_CONTRACTS);
|
||||
const openRows = (await inst.db.select().from(schema.packages)).filter((p) => p.status === 'open');
|
||||
expect(openRows.length).toBe(MARKET_TARGET_OPEN_PACKAGES);
|
||||
|
||||
const fc = await loadAirportsGeoJson();
|
||||
const icaoSet = new Set(fc.features.map((f) => f.properties.icao));
|
||||
for (const c of openRows.slice(3)) { // the spawned ones
|
||||
expect(c.createdSimTime).toBe(clock); // created at game time, not real time
|
||||
expect(icaoSet.has(c.originIcao)).toBe(true);
|
||||
expect(icaoSet.has(c.destIcao)).toBe(true);
|
||||
expect(c.originIcao).not.toBe(c.destIcao);
|
||||
expect(c.planeId).toBeNull();
|
||||
for (const p of openRows.slice(3)) { // the spawned ones
|
||||
expect(p.createdSimTime).toBe(clock); // created at game time, not real time
|
||||
expect(icaoSet.has(p.originIcao)).toBe(true);
|
||||
expect(icaoSet.has(p.destIcao)).toBe(true);
|
||||
expect(p.originIcao).not.toBe(p.destIcao);
|
||||
expect(p.planeId).toBeNull();
|
||||
// Same deadline window as the seed: now + 6–72h game time.
|
||||
expect(c.deadlineSimTime).toBeGreaterThan(clock + 6 * 3_600_000 - 1);
|
||||
expect(c.deadlineSimTime).toBeLessThanOrEqual(clock + 72 * 3_600_000);
|
||||
expect(p.deadlineSimTime).toBeGreaterThan(clock + 6 * 3_600_000 - 1);
|
||||
expect(p.deadlineSimTime).toBeLessThanOrEqual(clock + 72 * 3_600_000);
|
||||
}
|
||||
|
||||
// Already at target → nothing more to spawn.
|
||||
expect(await spawnOpenContracts(inst, clock, mulberry32(7))).toBe(0);
|
||||
expect(await spawnOpenPackages(inst, clock, mulberry32(7))).toBe(0);
|
||||
});
|
||||
|
||||
it('is deterministic for an injected RNG (spawn matches the seed builder)', async () => {
|
||||
@@ -239,103 +272,103 @@ describe('spawnOpenContracts', () => {
|
||||
const b = await freshDb('spawn-b.db');
|
||||
const clock = T0 + 999;
|
||||
|
||||
// Wipe all contracts in both so both spawn from zero with the same RNG.
|
||||
// Wipe all packages in both so both spawn from zero with the same RNG.
|
||||
for (const inst of [a, b]) {
|
||||
const rows = await inst.db.select().from(schema.contracts);
|
||||
const rows = await inst.db.select().from(schema.packages);
|
||||
for (const r of rows) {
|
||||
await inst.db.delete(schema.contracts).where(eq(schema.contracts.id, r.id));
|
||||
await inst.db.delete(schema.packages).where(eq(schema.packages.id, r.id));
|
||||
}
|
||||
}
|
||||
|
||||
expect(await spawnOpenContracts(a, clock, mulberry32(42))).toBe(MARKET_TARGET_OPEN_CONTRACTS);
|
||||
expect(await spawnOpenContracts(b, clock, mulberry32(42))).toBe(MARKET_TARGET_OPEN_CONTRACTS);
|
||||
expect(await spawnOpenPackages(a, clock, mulberry32(42))).toBe(MARKET_TARGET_OPEN_PACKAGES);
|
||||
expect(await spawnOpenPackages(b, clock, mulberry32(42))).toBe(MARKET_TARGET_OPEN_PACKAGES);
|
||||
|
||||
const strip = (rows: schema.ContractRow[]) =>
|
||||
rows.filter((c) => c.status === 'open').map(({ id: _id, ...rest }) => JSON.stringify(rest)).sort();
|
||||
expect(strip(await a.db.select().from(schema.contracts))).toEqual(
|
||||
strip(await b.db.select().from(schema.contracts)),
|
||||
const strip = (rows: schema.PackageRow[]) =>
|
||||
rows.filter((p) => p.status === 'open').map(({ id: _id, ...rest }) => JSON.stringify(rest)).sort();
|
||||
expect(strip(await a.db.select().from(schema.packages))).toEqual(
|
||||
strip(await b.db.select().from(schema.packages)),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('spawnCoverageContracts (v0.8.0 spawn coverage rule)', () => {
|
||||
// The seeded starter plane is grounded at EDDF with no seeded contract from
|
||||
describe('spawnCoveragePackages (v0.8.0 spawn coverage rule)', () => {
|
||||
// The seeded starter plane is grounded at EDDF with no seeded package from
|
||||
// there, so a fresh DB always has exactly one uncovered airport: EDDF.
|
||||
|
||||
it('spawns an open contract originating at the airport of each uncovered grounded plane', async () => {
|
||||
it('spawns an open package originating at the airport of each uncovered grounded plane', async () => {
|
||||
const inst = await freshDb('coverage.db');
|
||||
const clock = T0 + 5_000;
|
||||
|
||||
// Wipe all seeded contracts so coverage is the only source of new ones.
|
||||
for (const c of await inst.db.select().from(schema.contracts)) {
|
||||
await inst.db.delete(schema.contracts).where(eq(schema.contracts.id, c.id));
|
||||
// Wipe all seeded packages so coverage is the only source of new ones.
|
||||
for (const p of await inst.db.select().from(schema.packages)) {
|
||||
await inst.db.delete(schema.packages).where(eq(schema.packages.id, p.id));
|
||||
}
|
||||
|
||||
const n = await spawnCoverageContracts(inst, clock, mulberry32(7));
|
||||
const n = await spawnCoveragePackages(inst, clock, mulberry32(7));
|
||||
expect(n).toBe(1); // only EDDF is uncovered (single grounded plane)
|
||||
|
||||
const openRows = (await inst.db.select().from(schema.contracts)).filter((c) => c.status === 'open');
|
||||
const openRows = (await inst.db.select().from(schema.packages)).filter((p) => p.status === 'open');
|
||||
expect(openRows.length).toBe(1);
|
||||
expect(openRows[0].originIcao).toBe('EDDF'); // origin forced to the plane's airport
|
||||
expect(openRows[0].createdSimTime).toBe(clock);
|
||||
});
|
||||
|
||||
it('does nothing when every grounded airport already has an open contract', async () => {
|
||||
it('does nothing when every grounded airport already has an open package', async () => {
|
||||
const inst = await freshDb('coverage-covered.db');
|
||||
for (const c of await inst.db.select().from(schema.contracts)) {
|
||||
await inst.db.delete(schema.contracts).where(eq(schema.contracts.id, c.id));
|
||||
for (const p of await inst.db.select().from(schema.packages)) {
|
||||
await inst.db.delete(schema.packages).where(eq(schema.packages.id, p.id));
|
||||
}
|
||||
// One open contract from EDDF covers the starter plane's airport.
|
||||
await inst.db.insert(schema.contracts).values({
|
||||
id: 'c-cover', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1,
|
||||
// One open package from EDDF covers the starter plane's airport.
|
||||
await inst.db.insert(schema.packages).values({
|
||||
id: 'p-cover', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1,
|
||||
deadlineSimTime: T0 + 3_600_000, status: 'open', planeId: null, createdSimTime: T0,
|
||||
});
|
||||
|
||||
expect(await spawnCoverageContracts(inst, T0 + 5_000, mulberry32(7))).toBe(0);
|
||||
expect((await inst.db.select().from(schema.contracts)).length).toBe(1); // nothing added
|
||||
expect(await spawnCoveragePackages(inst, T0 + 5_000, mulberry32(7))).toBe(0);
|
||||
expect((await inst.db.select().from(schema.packages)).length).toBe(1); // nothing added
|
||||
});
|
||||
|
||||
it('spawns one contract per uncovered airport when planes sit at several airports', async () => {
|
||||
it('spawns one package per uncovered airport when planes sit at several airports', async () => {
|
||||
const inst = await freshDb('coverage-multi.db');
|
||||
for (const c of await inst.db.select().from(schema.contracts)) {
|
||||
await inst.db.delete(schema.contracts).where(eq(schema.contracts.id, c.id));
|
||||
for (const p of await inst.db.select().from(schema.packages)) {
|
||||
await inst.db.delete(schema.packages).where(eq(schema.packages.id, p.id));
|
||||
}
|
||||
// A second grounded plane at LEMD; two planes sharing EDDF must not double-spawn.
|
||||
await inst.db.insert(schema.planes).values([
|
||||
{ id: 'p-2', model: 'atr72', status: 'available', fuel: 100, maxFuel: 6300, locationIcao: 'LEMD', contractId: null, lat: 40.4, lon: -3.6, departureSimTime: null },
|
||||
{ id: 'p-3', model: 'atr72', status: 'available', fuel: 100, maxFuel: 6300, locationIcao: 'EDDF', contractId: null, lat: 50.03, lon: 8.57, departureSimTime: null },
|
||||
{ id: 'p-2', model: 'atr72', status: 'available', fuel: 100, maxFuel: 6300, locationIcao: 'LEMD', destIcao: null, lat: 40.4, lon: -3.6, departureSimTime: null },
|
||||
{ id: 'p-3', model: 'atr72', status: 'available', fuel: 100, maxFuel: 6300, locationIcao: 'EDDF', destIcao: null, lat: 50.03, lon: 8.57, departureSimTime: null },
|
||||
]);
|
||||
|
||||
const n = await spawnCoverageContracts(inst, T0 + 5_000, mulberry32(7));
|
||||
expect(n).toBe(2); // EDDF (×2 planes → one contract) and LEMD
|
||||
const n = await spawnCoveragePackages(inst, T0 + 5_000, mulberry32(7));
|
||||
expect(n).toBe(2); // EDDF (×2 planes → one package) and LEMD
|
||||
|
||||
const origins = (await inst.db.select().from(schema.contracts))
|
||||
.filter((c) => c.status === 'open')
|
||||
.map((c) => c.originIcao)
|
||||
const origins = (await inst.db.select().from(schema.packages))
|
||||
.filter((p) => p.status === 'open')
|
||||
.map((p) => p.originIcao)
|
||||
.sort();
|
||||
expect(origins).toEqual(['EDDF', 'LEMD']);
|
||||
});
|
||||
|
||||
it('ignores flying planes — they cannot take new work until they land', async () => {
|
||||
const inst = await freshDb('coverage-flying.db');
|
||||
for (const c of await inst.db.select().from(schema.contracts)) {
|
||||
await inst.db.delete(schema.contracts).where(eq(schema.contracts.id, c.id));
|
||||
for (const p of await inst.db.select().from(schema.packages)) {
|
||||
await inst.db.delete(schema.packages).where(eq(schema.packages.id, p.id));
|
||||
}
|
||||
await inst.db.update(schema.planes)
|
||||
.set({ status: 'flying', departureSimTime: T0, contractId: 'c-gone' })
|
||||
.set({ status: 'flying', departureSimTime: T0, destIcao: 'LEMD' })
|
||||
.where(eq(schema.planes.id, 'plane-starter'));
|
||||
|
||||
expect(await spawnCoverageContracts(inst, T0 + 5_000, mulberry32(7))).toBe(0); // no grounded planes
|
||||
expect(await spawnCoveragePackages(inst, T0 + 5_000, mulberry32(7))).toBe(0); // no grounded planes
|
||||
});
|
||||
|
||||
it('runs inside tickOnce: a fresh DB gains an EDDF-origin contract after one advancing tick', async () => {
|
||||
it('runs inside tickOnce: a fresh DB gains an EDDF-origin package after one advancing tick', async () => {
|
||||
const inst = await freshDb('coverage-tick.db');
|
||||
vi.setSystemTime(T0 + 1_000); // one real second → advanceMs > 0 at scale 1
|
||||
|
||||
await tickOnce(inst);
|
||||
|
||||
const fromEdff = (await inst.db.select().from(schema.contracts)).filter(
|
||||
(c) => c.status === 'open' && c.originIcao === 'EDDF',
|
||||
const fromEdff = (await inst.db.select().from(schema.packages)).filter(
|
||||
(p) => p.status === 'open' && p.originIcao === 'EDDF',
|
||||
);
|
||||
expect(fromEdff.length).toBeGreaterThanOrEqual(1); // coverage held through the full tick pipeline
|
||||
});
|
||||
|
||||
+66
-54
@@ -1,13 +1,13 @@
|
||||
import { randomInt, randomUUID } from 'node:crypto';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { eq, inArray } from 'drizzle-orm';
|
||||
import { getGameDb, persist, type GameDb } from '@/lib/db/client';
|
||||
import * as schema from '@/lib/db/schema';
|
||||
import { loadAirportsGeoJson } from '@/lib/airports';
|
||||
import { haversineKm } from '@/lib/geo';
|
||||
import { PLANE_TYPES } from '@/lib/game/catalog';
|
||||
import {
|
||||
generateContract,
|
||||
MARKET_TARGET_OPEN_CONTRACTS,
|
||||
generatePackage,
|
||||
MARKET_TARGET_OPEN_PACKAGES,
|
||||
mulberry32,
|
||||
type Rng,
|
||||
type SeedAirport,
|
||||
@@ -29,7 +29,7 @@ export const MAX_TICK_ELAPSED_MS = 2_000;
|
||||
export const MIN_TIME_SCALE = 1;
|
||||
export const MAX_TIME_SCALE = 64; // top of the power-of-two ladder (v0.9.2)
|
||||
|
||||
// Reputation gain per completed contract: BASE + PER_KM × great-circle km, rounded
|
||||
// Reputation gain per delivered package: BASE + PER_KM × great-circle km, rounded
|
||||
// to 2 decimals (reputation is REAL). A short hop (~300 km) earns ~1.15 rep, a
|
||||
// cross-Europe leg (~3000 km) ~2.5 — slow growth from the starting 10.
|
||||
export const REP_BASE = 1;
|
||||
@@ -72,12 +72,12 @@ export async function tickOnce(inst: GameDb): Promise<schema.SimStateRow> {
|
||||
const clockMs = Math.round(sim.clockMs + advanceMs);
|
||||
|
||||
if (advanceMs > 0) {
|
||||
await expireContracts(inst, clockMs);
|
||||
await finalizeArrivals(inst, clockMs);
|
||||
await spawnOpenContracts(inst, clockMs);
|
||||
// AFTER finalization on purpose: a plane that just landed gets work spawned
|
||||
await expirePackages(inst, clockMs);
|
||||
await deliverPackages(inst, clockMs);
|
||||
await spawnOpenPackages(inst, clockMs);
|
||||
// AFTER delivery on purpose: a plane that just landed gets work spawned
|
||||
// at its new location within the same tick.
|
||||
await spawnCoverageContracts(inst, clockMs);
|
||||
await spawnCoveragePackages(inst, clockMs);
|
||||
}
|
||||
|
||||
// Persist lastRealTickMs even when nothing advanced — it is the tick anchor.
|
||||
@@ -88,42 +88,45 @@ export async function tickOnce(inst: GameDb): Promise<schema.SimStateRow> {
|
||||
return updated;
|
||||
}
|
||||
|
||||
// Open contracts whose deadline has passed become 'expired'. Accepted/in-flight
|
||||
// contracts never expire — they complete. Returns the number flipped.
|
||||
export async function expireContracts(inst: GameDb, clockMs: number): Promise<number> {
|
||||
const open = await inst.db.select().from(schema.contracts).where(eq(schema.contracts.status, 'open'));
|
||||
// Packages whose deadline has passed become 'expired' — both OPEN ones (they leave
|
||||
// the market so spawn can top it back up) and LOADED ones (v0.12.0: they keep
|
||||
// occupying their slot, deliver no reward on arrival, and abandon for free).
|
||||
// Delivered/abandoned packages are terminal and never flip. Returns the count.
|
||||
export async function expirePackages(inst: GameDb, clockMs: number): Promise<number> {
|
||||
const rows = await inst.db.select().from(schema.packages).where(inArray(schema.packages.status, ['open', 'loaded']));
|
||||
let n = 0;
|
||||
for (const c of open) {
|
||||
if (c.deadlineSimTime <= clockMs) {
|
||||
await inst.db.update(schema.contracts).set({ status: 'expired' }).where(eq(schema.contracts.id, c.id));
|
||||
for (const p of rows) {
|
||||
if (p.deadlineSimTime <= clockMs) {
|
||||
await inst.db.update(schema.packages).set({ status: 'expired' }).where(eq(schema.packages.id, p.id));
|
||||
n++;
|
||||
}
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
// Finalize in-flight planes whose arrival time has passed: award the contract
|
||||
// reward (cash) + reputation gain exactly once, mark the contract completed, and
|
||||
// ground the plane at the destination with its remaining fuel. Idempotent — a
|
||||
// finalized plane leaves the 'flying' state, so it can never be awarded twice.
|
||||
export async function finalizeArrivals(inst: GameDb, clockMs: number): Promise<number> {
|
||||
const [planeRows, contractRows] = await Promise.all([
|
||||
// Finalize in-flight planes whose arrival time has passed (v0.12.0 delivery):
|
||||
// ground the plane at its dest_icao with its remaining fuel, then for every
|
||||
// package bound to it and destined for that airport — 'loaded' ones still inside
|
||||
// their deadline are delivered (cash += reward + reputation gain per package),
|
||||
// 'expired' ones just unbind (no reward). Packages destined elsewhere stay loaded
|
||||
// on the plane for a later leg. Idempotent — a finalized plane leaves the
|
||||
// 'flying' state, so it can never be awarded twice. Returns planes landed.
|
||||
export async function deliverPackages(inst: GameDb, clockMs: number): Promise<number> {
|
||||
const [planeRows, packageRows] = await Promise.all([
|
||||
inst.db.select().from(schema.planes),
|
||||
inst.db.select().from(schema.contracts),
|
||||
inst.db.select().from(schema.packages),
|
||||
]);
|
||||
|
||||
const fc = await loadAirportsGeoJson();
|
||||
const byIcao = new Map(fc.features.map((f) => [f.properties.icao, f.properties]));
|
||||
const contractById = new Map(contractRows.map((c) => [c.id, c]));
|
||||
|
||||
let n = 0;
|
||||
for (const p of planeRows) {
|
||||
if (p.status !== 'flying' || p.departureSimTime == null || !p.contractId) continue;
|
||||
const contract = contractById.get(p.contractId);
|
||||
if (p.status !== 'flying' || p.departureSimTime == null || !p.destIcao) continue;
|
||||
const type = PLANE_TYPES[p.model];
|
||||
const from = contract ? byIcao.get(contract.originIcao) : undefined;
|
||||
const to = contract ? byIcao.get(contract.destIcao) : undefined;
|
||||
if (!contract || !type || !from || !to) continue; // no route info — leave alone
|
||||
const from = byIcao.get(p.locationIcao);
|
||||
const to = byIcao.get(p.destIcao);
|
||||
if (!type || !from || !to) continue; // no route info — leave alone
|
||||
|
||||
const distanceKm = haversineKm(from.lat, from.lon, to.lat, to.lon);
|
||||
if (clockMs < arrivalTimeFor(p.departureSimTime, distanceKm, type.speedKmh)) continue;
|
||||
@@ -137,35 +140,44 @@ export async function finalizeArrivals(inst: GameDb, clockMs: number): Promise<n
|
||||
lon: to.lon,
|
||||
fuel: fuelAt(p.fuel, type.burnPerKm, distanceKm, 1),
|
||||
departureSimTime: null,
|
||||
destIcao: null,
|
||||
})
|
||||
.where(eq(schema.planes.id, p.id));
|
||||
await inst.db.update(schema.contracts)
|
||||
.set({ status: 'completed' })
|
||||
.where(eq(schema.contracts.id, contract.id));
|
||||
// Fresh account read per award so multiple arrivals in one tick all count.
|
||||
const fresh = (await inst.db.select().from(schema.account))[0];
|
||||
if (!fresh) throw new Error('account row missing');
|
||||
await inst.db.update(schema.account).set({
|
||||
cash: fresh.cash + contract.reward,
|
||||
reputation: Math.round((fresh.reputation + reputationGainFor(distanceKm)) * 100) / 100,
|
||||
});
|
||||
|
||||
// Deliver every bound package whose destination is the airport just reached.
|
||||
const onBoard = packageRows.filter((pk) => pk.planeId === p.id && pk.destIcao === to.icao);
|
||||
for (const pk of onBoard) {
|
||||
if (pk.status === 'loaded' && clockMs <= pk.deadlineSimTime) {
|
||||
await inst.db.update(schema.packages).set({ status: 'delivered' }).where(eq(schema.packages.id, pk.id));
|
||||
// Fresh account read per award so multiple deliveries in one tick all count.
|
||||
const fresh = (await inst.db.select().from(schema.account))[0];
|
||||
if (!fresh) throw new Error('account row missing');
|
||||
await inst.db.update(schema.account).set({
|
||||
cash: fresh.cash + pk.reward,
|
||||
reputation: Math.round((fresh.reputation + reputationGainFor(distanceKm)) * 100) / 100,
|
||||
});
|
||||
} else if (pk.status === 'expired') {
|
||||
// Expired cargo keeps no value — just free the slot.
|
||||
await inst.db.update(schema.packages).set({ planeId: null }).where(eq(schema.packages.id, pk.id));
|
||||
}
|
||||
}
|
||||
n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
// Top the market back up to MARKET_TARGET_OPEN_CONTRACTS open contracts using the
|
||||
// SAME builder as the first-run seed (generateContract), so spawned contracts are
|
||||
// Top the market back up to MARKET_TARGET_OPEN_PACKAGES open packages using the
|
||||
// SAME builder as the first-run seed (generatePackage), so spawned packages are
|
||||
// indistinguishable from seeded ones. RNG is injectable for deterministic tests.
|
||||
export async function spawnOpenContracts(
|
||||
export async function spawnOpenPackages(
|
||||
inst: GameDb,
|
||||
clockMs: number,
|
||||
rng?: Rng,
|
||||
): Promise<number> {
|
||||
const openCount = (
|
||||
await inst.db.select().from(schema.contracts).where(eq(schema.contracts.status, 'open'))
|
||||
await inst.db.select().from(schema.packages).where(eq(schema.packages.status, 'open'))
|
||||
).length;
|
||||
const needed = MARKET_TARGET_OPEN_CONTRACTS - openCount;
|
||||
const needed = MARKET_TARGET_OPEN_PACKAGES - openCount;
|
||||
if (needed <= 0) return 0;
|
||||
|
||||
const fc = await loadAirportsGeoJson();
|
||||
@@ -178,27 +190,27 @@ export async function spawnOpenContracts(
|
||||
const rand = rng ?? mulberry32(randomInt(0, 2 ** 31));
|
||||
|
||||
for (let i = 0; i < needed; i++) {
|
||||
await inst.db.insert(schema.contracts).values(generateContract({ id: randomUUID(), airports, rng: rand, nowMs: clockMs }));
|
||||
await inst.db.insert(schema.packages).values(generatePackage({ id: randomUUID(), airports, rng: rand, nowMs: clockMs }));
|
||||
}
|
||||
return needed;
|
||||
}
|
||||
|
||||
// Spawn coverage rule (v0.8.0): in addition to topping the market up, every
|
||||
// airport that currently has a grounded 'available' plane must have ≥1 OPEN
|
||||
// contract originating there — so work is always available where the fleet sits
|
||||
// (including onboarding at EDDF). One contract per uncovered airport, generated
|
||||
// with generateContract and origin forced to that airport. Runs after
|
||||
// spawnOpenContracts in tickOnce, so randomly spawned contracts count as coverage
|
||||
// too; and after finalizeArrivals, so a plane that just landed gets work spawned
|
||||
// package originating there — so work is always available where the fleet sits
|
||||
// (including onboarding at EDDF). One package per uncovered airport, generated
|
||||
// with generatePackage and origin forced to that airport. Runs after
|
||||
// spawnOpenPackages in tickOnce, so randomly spawned packages count as coverage
|
||||
// too; and after deliverPackages, so a plane that just landed gets work spawned
|
||||
// at its new location within the same tick. Returns the number created.
|
||||
export async function spawnCoverageContracts(
|
||||
export async function spawnCoveragePackages(
|
||||
inst: GameDb,
|
||||
clockMs: number,
|
||||
rng?: Rng,
|
||||
): Promise<number> {
|
||||
const [planeRows, openRows] = await Promise.all([
|
||||
inst.db.select().from(schema.planes),
|
||||
inst.db.select().from(schema.contracts).where(eq(schema.contracts.status, 'open')),
|
||||
inst.db.select().from(schema.packages).where(eq(schema.packages.status, 'open')),
|
||||
]);
|
||||
|
||||
// Distinct airports with at least one grounded plane (flying planes don't count —
|
||||
@@ -224,8 +236,8 @@ export async function spawnCoverageContracts(
|
||||
let n = 0;
|
||||
for (const icao of missing) {
|
||||
if (!airports.some((a) => a.icao === icao)) continue; // defensive — the dataset is the source of all ICACs
|
||||
await inst.db.insert(schema.contracts).values(
|
||||
generateContract({ id: randomUUID(), airports, rng: rand, nowMs: clockMs, originIcao: icao }),
|
||||
await inst.db.insert(schema.packages).values(
|
||||
generatePackage({ id: randomUUID(), airports, rng: rand, nowMs: clockMs, originIcao: icao }),
|
||||
);
|
||||
n++;
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ const SNAPSHOT = {
|
||||
account: { cash: 20_000, reputation: 10 },
|
||||
simState: { clockMs: 1_750_000_000_000, timeScale: 1, paused: false },
|
||||
planes: [],
|
||||
contracts: [],
|
||||
packages: [],
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
|
||||
Reference in New Issue
Block a user