feat(api): ship + research endpoints queue tasks with lead + helpers; mission accept is instant and free (#44)
CI / build + unit + e2e (pull_request) Failing after 3m58s
CI / build + unit + e2e (pull_request) Failing after 3m58s
This commit is contained in:
@@ -0,0 +1,96 @@
|
||||
// Handler-level tests for the queueing ship-build route (Task 5a(ii)): POST /api/ship/build
|
||||
// with a crew team queues a SHIP_BUILD row instead of resolving instantly — the build at
|
||||
// base values waits for the turn tick, the flat parts cost comes out of the cargo hold at
|
||||
// queue time, same snapshot shape, same pre-check codes, no turn spent at queue time.
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { afterAll, describe, expect, it } from 'vitest'
|
||||
import { getGameDb, type GameDb } from '@/lib/db/client'
|
||||
import * as schema from '@/lib/db/schema'
|
||||
import { getShipState } from '@/lib/game/ship'
|
||||
import { BUILD_PART_COST } from '@/lib/game/ship-costs'
|
||||
import { addCrew, buildWorldFixture } from '@/lib/game/test-fixtures'
|
||||
import { POST } from './route'
|
||||
|
||||
const dirs: string[] = []
|
||||
// The route talks to the app-process singleton (getGameDb), so each test points it at a
|
||||
// fresh temp file and uses that very instance for fixtures and assertions — two in-memory
|
||||
// sql.js copies of one file would never see each other's writes.
|
||||
const g = globalThis as unknown as { __spaceWandererGameDb?: Promise<GameDb> }
|
||||
|
||||
async function freshFile(): Promise<{ db: GameDb; file: string }> {
|
||||
const dir = await mkdtemp(path.join(tmpdir(), 'sw-ship-build-route-test-'))
|
||||
dirs.push(dir)
|
||||
const file = path.join(dir, 'test.db')
|
||||
process.env.SPACE_WANDERER_DB_PATH = file
|
||||
delete g.__spaceWandererGameDb
|
||||
return { db: await getGameDb(), file }
|
||||
}
|
||||
|
||||
afterAll(async () => {
|
||||
delete process.env.SPACE_WANDERER_DB_PATH
|
||||
delete g.__spaceWandererGameDb
|
||||
for (const d of dirs) await rm(d, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
const post = (body: unknown) => POST(new Request('http://localhost/api/ship/build', { method: 'POST', body: JSON.stringify(body) }))
|
||||
|
||||
// The fixture suite mints no ship rows (JC-6) — insert exactly what the test needs. HULL is
|
||||
// the only type that is unbuilt by default AND has no build gate (WEAPONS is gated behind
|
||||
// the WEAPONS SYSTEMS tech, which the fixture leaves unresearched).
|
||||
async function insertSystem(db: GameDb, over: { type: string; level: number; capacity: number }) {
|
||||
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||
const [row] = await db.db.insert(schema.shipSystems).values({ saveId: save.id, ...over }).returning()
|
||||
return row
|
||||
}
|
||||
|
||||
// The fixture suite mints no cargo hold (JC-6) — seed rows directly.
|
||||
async function seedHold(db: GameDb, rows: { kind: 'resource' | 'part'; name: string; qty: number }[]) {
|
||||
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||
for (const r of rows) {
|
||||
await db.db.insert(schema.inventoryItems).values({ saveId: save.id, ...r })
|
||||
}
|
||||
}
|
||||
|
||||
describe('POST /api/ship/build (5a(ii))', () => {
|
||||
it('happy: row with type/payload, turn unchanged, parts deducted, not built yet', async () => {
|
||||
const { db } = await freshFile()
|
||||
await buildWorldFixture(db)
|
||||
const [c1] = await addCrew(db, 1)
|
||||
const sys = await insertSystem(db, { type: 'HULL', level: 0, capacity: 0 }) // unbuilt, no gate
|
||||
await seedHold(db, [{ kind: 'part', name: 'part', qty: BUILD_PART_COST }]) // exactly the existing flat cost
|
||||
const [before] = await db.db.select().from(schema.saves)
|
||||
|
||||
const res = await post({ type: sys.type, leadCrewId: c1 })
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual(await getShipState(db)) // the same snapshot shape the instant action returned
|
||||
const [row] = await db.db.select().from(schema.tasks)
|
||||
expect(row).toMatchObject({ type: 'SHIP_BUILD', leadCrewId: c1, status: 'ACTIVE', queuedAtTurn: before.turn })
|
||||
expect(JSON.parse(row.helpers)).toEqual([]) // helpers is a JSON text column
|
||||
expect(JSON.parse(row.payload)).toEqual({ type: sys.type })
|
||||
expect((await db.db.select().from(schema.saves))[0].turn).toBe(before.turn) // no turn increment
|
||||
expect(await db.db.select().from(schema.inventoryItems)).toHaveLength(0) // whole cost deducted at queue time
|
||||
expect((await db.db.select().from(schema.shipSystems)).find((s) => s.id === sys.id)!.level).toBe(0) // the effect waits for the tick
|
||||
})
|
||||
|
||||
it('unaffordable → 422 (existing spendItems message), nothing queued', async () => {
|
||||
const { db } = await freshFile()
|
||||
await buildWorldFixture(db)
|
||||
const [c1] = await addCrew(db, 1)
|
||||
await insertSystem(db, { type: 'HULL', level: 0, capacity: 0 })
|
||||
await seedHold(db, [{ kind: 'part', name: 'part', qty: BUILD_PART_COST - 1 }])
|
||||
const res = await post({ type: 'HULL', leadCrewId: c1 })
|
||||
expect(res.status).toBe(422)
|
||||
expect(await db.db.select().from(schema.tasks)).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('already built → 409 (existing pre-check, existing code), nothing queued', async () => {
|
||||
const { db } = await freshFile()
|
||||
await buildWorldFixture(db)
|
||||
const [c1] = await addCrew(db, 1)
|
||||
const sys = await insertSystem(db, { type: 'HULL', level: 1, capacity: 2 }) // built at base values
|
||||
expect((await post({ type: sys.type, leadCrewId: c1 })).status).toBe(409)
|
||||
expect(await db.db.select().from(schema.tasks)).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
@@ -1,8 +1,14 @@
|
||||
import { getGameDb } from '@/lib/db/client'
|
||||
import { ShipError, buildSystem } from '@/lib/game/ship'
|
||||
import { parseCrewTeam } from '@/app/api/crew-team'
|
||||
import { checkBuildPreconditions, getShipState, ShipError } from '@/lib/game/ship'
|
||||
import { queueStateFromSave, saveInventory, saveTaskRow } from '@/lib/game/save'
|
||||
import { queueTask, TaskError } from '@/lib/game/tasks'
|
||||
|
||||
// Build an unbuilt ship system type at base values. Body: { "type": string }.
|
||||
// Costs inventory items + a turn; returns the fresh ship state.
|
||||
// Build an unbuilt ship system type at base values: assign the crew team (lead + helpers)
|
||||
// and queue the SHIP_BUILD task — the flat parts cost is deducted at queue time and the
|
||||
// build lands when the task completes on the turn tick (runTurn). Body:
|
||||
// { type, leadCrewId, helperCrewIds? }. Queueing spends no turn; returns the same fresh
|
||||
// ship state the instant action returned.
|
||||
export async function POST(req: Request) {
|
||||
let body: unknown
|
||||
try {
|
||||
@@ -15,12 +21,21 @@ export async function POST(req: Request) {
|
||||
if (typeof type !== 'string' || type.length === 0) {
|
||||
return Response.json({ error: 'type must be a non-empty string' }, { status: 400 })
|
||||
}
|
||||
const team = parseCrewTeam(body)
|
||||
if ('error' in team) {
|
||||
return Response.json({ error: team.error }, { status: team.status })
|
||||
}
|
||||
|
||||
try {
|
||||
const db = await getGameDb()
|
||||
return Response.json(await buildSystem(db, type))
|
||||
await checkBuildPreconditions(db, type) // existing pre-checks: 404 unknown type · 409 already built / build gate
|
||||
const state = await queueStateFromSave(db)
|
||||
const { task, inventory } = queueTask(state, { type: 'SHIP_BUILD', payload: { type }, leadCrewId: team.leadCrewId, helperCrewIds: team.helperCrewIds })
|
||||
await saveTaskRow(db, task)
|
||||
await saveInventory(db, inventory) // the cost was deducted at queue time
|
||||
return Response.json(await getShipState(db))
|
||||
} catch (err) {
|
||||
if (err instanceof ShipError) {
|
||||
if (err instanceof ShipError || err instanceof TaskError) {
|
||||
return Response.json({ error: err.message }, { status: err.status })
|
||||
}
|
||||
throw err
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
// Handler-level tests for the queueing ship-expand route (Task 5a(ii)): POST /api/ship/expand
|
||||
// with a crew team queues a SHIP_EXPAND row instead of resolving instantly — the capacity
|
||||
// bump waits for the turn tick, the cost comes out of the cargo hold at queue time, same
|
||||
// snapshot shape, same pre-check codes, no turn spent at queue time.
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { afterAll, describe, expect, it } from 'vitest'
|
||||
import { getGameDb, type GameDb } from '@/lib/db/client'
|
||||
import * as schema from '@/lib/db/schema'
|
||||
import { getShipState } from '@/lib/game/ship'
|
||||
import { expandCost } from '@/lib/game/ship-costs'
|
||||
import { addCrew, buildWorldFixture } from '@/lib/game/test-fixtures'
|
||||
import { POST } from './route'
|
||||
|
||||
const dirs: string[] = []
|
||||
// The route talks to the app-process singleton (getGameDb), so each test points it at a
|
||||
// fresh temp file and uses that very instance for fixtures and assertions — two in-memory
|
||||
// sql.js copies of one file would never see each other's writes.
|
||||
const g = globalThis as unknown as { __spaceWandererGameDb?: Promise<GameDb> }
|
||||
|
||||
async function freshFile(): Promise<{ db: GameDb; file: string }> {
|
||||
const dir = await mkdtemp(path.join(tmpdir(), 'sw-ship-expand-route-test-'))
|
||||
dirs.push(dir)
|
||||
const file = path.join(dir, 'test.db')
|
||||
process.env.SPACE_WANDERER_DB_PATH = file
|
||||
delete g.__spaceWandererGameDb
|
||||
return { db: await getGameDb(), file }
|
||||
}
|
||||
|
||||
afterAll(async () => {
|
||||
delete process.env.SPACE_WANDERER_DB_PATH
|
||||
delete g.__spaceWandererGameDb
|
||||
for (const d of dirs) await rm(d, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
const post = (body: unknown) => POST(new Request('http://localhost/api/ship/expand', { method: 'POST', body: JSON.stringify(body) }))
|
||||
|
||||
// The fixture suite mints no ship rows (JC-6) — insert exactly what the test needs.
|
||||
async function insertSystem(db: GameDb, over: { type: string; level: number; capacity: number }) {
|
||||
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||
const [row] = await db.db.insert(schema.shipSystems).values({ saveId: save.id, ...over }).returning()
|
||||
return row
|
||||
}
|
||||
|
||||
// The fixture suite mints no cargo hold (JC-6) — seed rows directly.
|
||||
async function seedHold(db: GameDb, rows: { kind: 'resource' | 'part'; name: string; qty: number }[]) {
|
||||
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||
for (const r of rows) {
|
||||
await db.db.insert(schema.inventoryItems).values({ saveId: save.id, ...r })
|
||||
}
|
||||
}
|
||||
|
||||
describe('POST /api/ship/expand (5a(ii))', () => {
|
||||
it('happy: row with type/payload, turn unchanged, cost deducted, no capacity change yet', async () => {
|
||||
const { db } = await freshFile()
|
||||
await buildWorldFixture(db)
|
||||
const [c1] = await addCrew(db, 1)
|
||||
const sys = await insertSystem(db, { type: 'REACTOR', level: 1, capacity: 2 }) // built, not maxed (base cap 10)
|
||||
await seedHold(db, [{ kind: 'resource', name: 'resource', qty: expandCost(sys.capacity) }]) // exactly the existing cost logic
|
||||
const [before] = await db.db.select().from(schema.saves)
|
||||
|
||||
const res = await post({ systemId: sys.id, leadCrewId: c1 })
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual(await getShipState(db)) // the same snapshot shape the instant action returned
|
||||
const [row] = await db.db.select().from(schema.tasks)
|
||||
expect(row).toMatchObject({ type: 'SHIP_EXPAND', leadCrewId: c1, status: 'ACTIVE', queuedAtTurn: before.turn })
|
||||
expect(JSON.parse(row.helpers)).toEqual([]) // helpers is a JSON text column
|
||||
expect(JSON.parse(row.payload)).toEqual({ systemId: sys.id })
|
||||
expect((await db.db.select().from(schema.saves))[0].turn).toBe(before.turn) // no turn increment
|
||||
expect(await db.db.select().from(schema.inventoryItems)).toHaveLength(0) // whole cost deducted at queue time
|
||||
expect((await db.db.select().from(schema.shipSystems)).find((s) => s.id === sys.id)!.capacity).toBe(sys.capacity) // the effect waits for the tick
|
||||
})
|
||||
|
||||
it('unaffordable → 422 (existing spendItems message), nothing queued', async () => {
|
||||
const { db } = await freshFile()
|
||||
await buildWorldFixture(db)
|
||||
const [c1] = await addCrew(db, 1)
|
||||
const sys = await insertSystem(db, { type: 'REACTOR', level: 1, capacity: 2 })
|
||||
await seedHold(db, [{ kind: 'resource', name: 'resource', qty: expandCost(sys.capacity) - 1 }])
|
||||
const res = await post({ systemId: sys.id, leadCrewId: c1 })
|
||||
expect(res.status).toBe(422)
|
||||
expect(await db.db.select().from(schema.tasks)).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('max capacity → 409 (existing pre-check, existing code), nothing queued', async () => {
|
||||
const { db } = await freshFile()
|
||||
await buildWorldFixture(db)
|
||||
const [c1] = await addCrew(db, 1)
|
||||
const sys = await insertSystem(db, { type: 'REACTOR', level: 1, capacity: 99 }) // above any max
|
||||
expect((await post({ systemId: sys.id, leadCrewId: c1 })).status).toBe(409)
|
||||
expect(await db.db.select().from(schema.tasks)).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
@@ -1,8 +1,14 @@
|
||||
import { getGameDb } from '@/lib/db/client'
|
||||
import { ShipError, expandSystem } from '@/lib/game/ship'
|
||||
import { parseCrewTeam } from '@/app/api/crew-team'
|
||||
import { checkExpandPreconditions, getShipState, ShipError } from '@/lib/game/ship'
|
||||
import { queueStateFromSave, saveInventory, saveTaskRow } from '@/lib/game/save'
|
||||
import { queueTask, TaskError } from '@/lib/game/tasks'
|
||||
|
||||
// Raise a built ship system's capacity by one (capped at max capacity). Body: { "systemId": number }.
|
||||
// Costs inventory items + a turn; returns the fresh ship state.
|
||||
// Raise a built ship system's capacity by one (capped at max capacity): assign the crew team
|
||||
// (lead + helpers) and queue the SHIP_EXPAND task — the cost (`capacity` units of any
|
||||
// resource) is deducted at queue time and the capacity bump lands when the task completes on
|
||||
// the turn tick (runTurn). Body: { systemId, leadCrewId, helperCrewIds? }. Queueing spends no
|
||||
// turn; returns the same fresh ship state the instant action returned.
|
||||
export async function POST(req: Request) {
|
||||
let body: unknown
|
||||
try {
|
||||
@@ -15,12 +21,21 @@ export async function POST(req: Request) {
|
||||
if (typeof systemId !== 'number' || !Number.isInteger(systemId)) {
|
||||
return Response.json({ error: 'systemId must be an integer' }, { status: 400 })
|
||||
}
|
||||
const team = parseCrewTeam(body)
|
||||
if ('error' in team) {
|
||||
return Response.json({ error: team.error }, { status: team.status })
|
||||
}
|
||||
|
||||
try {
|
||||
const db = await getGameDb()
|
||||
return Response.json(await expandSystem(db, systemId))
|
||||
await checkExpandPreconditions(db, systemId) // existing pre-checks: 404 unknown · 409 not built / max capacity
|
||||
const state = await queueStateFromSave(db)
|
||||
const { task, inventory } = queueTask(state, { type: 'SHIP_EXPAND', payload: { systemId }, leadCrewId: team.leadCrewId, helperCrewIds: team.helperCrewIds })
|
||||
await saveTaskRow(db, task)
|
||||
await saveInventory(db, inventory) // the cost was deducted at queue time
|
||||
return Response.json(await getShipState(db))
|
||||
} catch (err) {
|
||||
if (err instanceof ShipError) {
|
||||
if (err instanceof ShipError || err instanceof TaskError) {
|
||||
return Response.json({ error: err.message }, { status: err.status })
|
||||
}
|
||||
throw err
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
// Handler-level tests for the queueing ship-upgrade route (Task 5a(ii)): POST /api/ship/upgrade
|
||||
// with a crew team queues a SHIP_UPGRADE row instead of resolving instantly — the level-up
|
||||
// waits for the turn tick, the cost comes out of the cargo hold at queue time, same snapshot
|
||||
// shape, same pre-check codes, no turn spent at queue time.
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { afterAll, describe, expect, it } from 'vitest'
|
||||
import { getGameDb, type GameDb } from '@/lib/db/client'
|
||||
import * as schema from '@/lib/db/schema'
|
||||
import { getShipState } from '@/lib/game/ship'
|
||||
import { upgradeCost } from '@/lib/game/ship-costs'
|
||||
import { addCrew, buildWorldFixture } from '@/lib/game/test-fixtures'
|
||||
import { POST } from './route'
|
||||
|
||||
const dirs: string[] = []
|
||||
// The route talks to the app-process singleton (getGameDb), so each test points it at a
|
||||
// fresh temp file and uses that very instance for fixtures and assertions — two in-memory
|
||||
// sql.js copies of one file would never see each other's writes.
|
||||
const g = globalThis as unknown as { __spaceWandererGameDb?: Promise<GameDb> }
|
||||
|
||||
async function freshFile(): Promise<{ db: GameDb; file: string }> {
|
||||
const dir = await mkdtemp(path.join(tmpdir(), 'sw-ship-upgrade-route-test-'))
|
||||
dirs.push(dir)
|
||||
const file = path.join(dir, 'test.db')
|
||||
process.env.SPACE_WANDERER_DB_PATH = file
|
||||
delete g.__spaceWandererGameDb
|
||||
return { db: await getGameDb(), file }
|
||||
}
|
||||
|
||||
afterAll(async () => {
|
||||
delete process.env.SPACE_WANDERER_DB_PATH
|
||||
delete g.__spaceWandererGameDb
|
||||
for (const d of dirs) await rm(d, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
const post = (body: unknown) => POST(new Request('http://localhost/api/ship/upgrade', { method: 'POST', body: JSON.stringify(body) }))
|
||||
|
||||
// The fixture suite mints no ship rows (JC-6) — insert exactly what the test needs.
|
||||
async function insertSystem(db: GameDb, over: { type: string; level: number; capacity: number }) {
|
||||
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||
const [row] = await db.db.insert(schema.shipSystems).values({ saveId: save.id, ...over }).returning()
|
||||
return row
|
||||
}
|
||||
|
||||
// The fixture suite mints no cargo hold (JC-6) — seed rows directly.
|
||||
async function seedHold(db: GameDb, rows: { kind: 'resource' | 'part'; name: string; qty: number }[]) {
|
||||
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||
for (const r of rows) {
|
||||
await db.db.insert(schema.inventoryItems).values({ saveId: save.id, ...r })
|
||||
}
|
||||
}
|
||||
|
||||
describe('POST /api/ship/upgrade (5a(ii))', () => {
|
||||
it('happy: row with type/payload, turn unchanged, cost deducted, no level change yet', async () => {
|
||||
const { db } = await freshFile()
|
||||
await buildWorldFixture(db)
|
||||
const [c1] = await addCrew(db, 1)
|
||||
const sys = await insertSystem(db, { type: 'REACTOR', level: 2, capacity: 2 }) // built, not maxed (base cap 5)
|
||||
await seedHold(db, [{ kind: 'resource', name: 'resource', qty: upgradeCost(sys.level) }]) // exactly the existing cost logic
|
||||
const [before] = await db.db.select().from(schema.saves)
|
||||
|
||||
const res = await post({ systemId: sys.id, leadCrewId: c1 })
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual(await getShipState(db)) // the same snapshot shape the instant action returned
|
||||
const [row] = await db.db.select().from(schema.tasks)
|
||||
expect(row).toMatchObject({ type: 'SHIP_UPGRADE', leadCrewId: c1, status: 'ACTIVE', queuedAtTurn: before.turn })
|
||||
expect(JSON.parse(row.helpers)).toEqual([]) // helpers is a JSON text column
|
||||
expect(JSON.parse(row.payload)).toEqual({ systemId: sys.id })
|
||||
expect((await db.db.select().from(schema.saves))[0].turn).toBe(before.turn) // no turn increment
|
||||
expect(await db.db.select().from(schema.inventoryItems)).toHaveLength(0) // whole cost deducted at queue time
|
||||
expect((await db.db.select().from(schema.shipSystems)).find((s) => s.id === sys.id)!.level).toBe(sys.level) // the effect waits for the tick
|
||||
})
|
||||
|
||||
it('unaffordable → 422 (existing spendItems message), nothing queued', async () => {
|
||||
const { db } = await freshFile()
|
||||
await buildWorldFixture(db)
|
||||
const [c1] = await addCrew(db, 1)
|
||||
const sys = await insertSystem(db, { type: 'REACTOR', level: 2, capacity: 2 })
|
||||
await seedHold(db, [{ kind: 'resource', name: 'resource', qty: upgradeCost(sys.level) - 1 }])
|
||||
const res = await post({ systemId: sys.id, leadCrewId: c1 })
|
||||
expect(res.status).toBe(422)
|
||||
expect(await db.db.select().from(schema.tasks)).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('max level → 409 (existing pre-check, existing code), nothing queued', async () => {
|
||||
const { db } = await freshFile()
|
||||
await buildWorldFixture(db)
|
||||
const [c1] = await addCrew(db, 1)
|
||||
const sys = await insertSystem(db, { type: 'REACTOR', level: 99, capacity: 2 }) // above any max
|
||||
expect((await post({ systemId: sys.id, leadCrewId: c1 })).status).toBe(409)
|
||||
expect(await db.db.select().from(schema.tasks)).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
@@ -1,8 +1,14 @@
|
||||
import { getGameDb } from '@/lib/db/client'
|
||||
import { ShipError, upgradeSystem } from '@/lib/game/ship'
|
||||
import { parseCrewTeam } from '@/app/api/crew-team'
|
||||
import { checkUpgradePreconditions, getShipState, ShipError } from '@/lib/game/ship'
|
||||
import { queueStateFromSave, saveInventory, saveTaskRow } from '@/lib/game/save'
|
||||
import { queueTask, TaskError } from '@/lib/game/tasks'
|
||||
|
||||
// Level up a built ship system by one (capped at max level). Body: { "systemId": number }.
|
||||
// Costs inventory items + a turn; returns the fresh ship state.
|
||||
// Level up a built ship system by one (capped at max level): assign the crew team (lead +
|
||||
// helpers) and queue the SHIP_UPGRADE task — the cost (`level` units of any resource) is
|
||||
// deducted at queue time and the level-up lands when the task completes on the turn tick
|
||||
// (runTurn). Body: { systemId, leadCrewId, helperCrewIds? }. Queueing spends no turn;
|
||||
// returns the same fresh ship state the instant action returned.
|
||||
export async function POST(req: Request) {
|
||||
let body: unknown
|
||||
try {
|
||||
@@ -15,12 +21,21 @@ export async function POST(req: Request) {
|
||||
if (typeof systemId !== 'number' || !Number.isInteger(systemId)) {
|
||||
return Response.json({ error: 'systemId must be an integer' }, { status: 400 })
|
||||
}
|
||||
const team = parseCrewTeam(body)
|
||||
if ('error' in team) {
|
||||
return Response.json({ error: team.error }, { status: team.status })
|
||||
}
|
||||
|
||||
try {
|
||||
const db = await getGameDb()
|
||||
return Response.json(await upgradeSystem(db, systemId))
|
||||
await checkUpgradePreconditions(db, systemId) // existing pre-checks: 404 unknown · 409 not built / max level
|
||||
const state = await queueStateFromSave(db)
|
||||
const { task, inventory } = queueTask(state, { type: 'SHIP_UPGRADE', payload: { systemId }, leadCrewId: team.leadCrewId, helperCrewIds: team.helperCrewIds })
|
||||
await saveTaskRow(db, task)
|
||||
await saveInventory(db, inventory) // the cost was deducted at queue time
|
||||
return Response.json(await getShipState(db))
|
||||
} catch (err) {
|
||||
if (err instanceof ShipError) {
|
||||
if (err instanceof ShipError || err instanceof TaskError) {
|
||||
return Response.json({ error: err.message }, { status: err.status })
|
||||
}
|
||||
throw err
|
||||
|
||||
Reference in New Issue
Block a user