355 lines
13 KiB
TypeScript
355 lines
13 KiB
TypeScript
import { expect, test } from "@playwright/test";
|
|
import type { Payload } from "payload";
|
|
import { resolveTestDatabaseUri } from "../test-db";
|
|
|
|
/**
|
|
* Interior system end-to-end smoke (plan Step 7 gate): enter the interior,
|
|
* open a sealed room, clean its junk, and collect the salvage.
|
|
*
|
|
* Data strategy mirrors garage.e2e.spec.ts: a purpose-built blueprint + game
|
|
* instance are created directly against the test database in beforeAll (the
|
|
* webServer env points DATABASE_URI at it), the UI drives every mutation, and
|
|
* only the sweep tick + one duration fast-forward go through the server-side
|
|
* libs because cron does not run under tests. The fixture is deleted after the
|
|
* suite so the run is repeatable.
|
|
*/
|
|
|
|
const NAME = "E2E Interior Station";
|
|
const CODE_NAME_BASE = "e2e-interior";
|
|
|
|
let payload: Payload;
|
|
let scrapId: number;
|
|
let instanceId: number;
|
|
|
|
async function loadPayload(): Promise<void> {
|
|
// global-setup.ts already points DATABASE_URI at the dedicated test database
|
|
// (its env mutations propagate to workers); re-deriving would append _test
|
|
// twice - see the same note in analytics.e2e.spec.ts.
|
|
if (!String(process.env.DATABASE_URI).endsWith("_test")) {
|
|
process.env.DATABASE_URI = resolveTestDatabaseUri();
|
|
}
|
|
const { getPayload } = await import("payload");
|
|
const { default: config } = await import("@payload-config");
|
|
payload = await getPayload({ config });
|
|
}
|
|
|
|
/** Interior libs read DATABASE_URI at import time: dynamic import after env is set. */
|
|
async function sweepInteriorJobsNow(): Promise<number> {
|
|
const { sweepInteriorJobs } = await import("@/lib/interior/sweep");
|
|
const result = await sweepInteriorJobs(payload as unknown as Parameters<typeof sweepInteriorJobs>[0]);
|
|
return result.completed;
|
|
}
|
|
|
|
async function ensureScrap(): Promise<number> {
|
|
const found = await payload.find({
|
|
collection: "resources",
|
|
where: { codeName: { equals: "res_scrap" } },
|
|
limit: 1,
|
|
overrideAccess: true,
|
|
});
|
|
if (found.docs[0]) return found.docs[0].id as number;
|
|
const created = await payload.create({
|
|
collection: "resources",
|
|
data: {
|
|
name: "E2E Scrap",
|
|
codeName: "res_scrap",
|
|
approvalStatus: "approved",
|
|
type: "physical",
|
|
unitOfMeasure: "kg",
|
|
massPerUnit: 0.2,
|
|
stackSize: 100,
|
|
stackable: true,
|
|
gridWidth: 1,
|
|
gridHeight: 1,
|
|
rotatable: false,
|
|
baseValue: 0,
|
|
rarity: "common",
|
|
tradeable: true,
|
|
},
|
|
draft: false,
|
|
overrideAccess: true,
|
|
});
|
|
return created.id as number;
|
|
}
|
|
|
|
async function makeFixture(): Promise<void> {
|
|
// Delete leftovers from interrupted runs so "Enter interior" is unambiguous.
|
|
const staleInstances = await payload.find({
|
|
collection: "game-structures",
|
|
where: { name: { equals: NAME } },
|
|
limit: 50,
|
|
overrideAccess: true,
|
|
});
|
|
for (const inst of staleInstances.docs) {
|
|
for (const [collection, where] of [
|
|
["interior-jobs", { structure: { equals: inst.id } }],
|
|
["structure-rooms", { structure: { equals: inst.id } }],
|
|
] as const) {
|
|
const rows = await payload.find({
|
|
collection,
|
|
where: where as never,
|
|
limit: 100,
|
|
overrideAccess: true,
|
|
});
|
|
for (const row of rows.docs) {
|
|
await payload
|
|
.delete({ collection, id: row.id as number, overrideAccess: true })
|
|
.catch(() => undefined);
|
|
}
|
|
}
|
|
await payload.delete({ collection: "game-structures", id: inst.id as number, overrideAccess: true }).catch(() => undefined);
|
|
}
|
|
const staleBlueprints = await payload.find({
|
|
collection: "structures",
|
|
where: { codeName: { like: `${CODE_NAME_BASE}%` } },
|
|
limit: 50,
|
|
overrideAccess: true,
|
|
});
|
|
for (const bp of staleBlueprints.docs) {
|
|
await payload.delete({ collection: "structures", id: bp.id as number, overrideAccess: true }).catch(() => undefined);
|
|
}
|
|
|
|
const blueprint = await payload.create({
|
|
collection: "structures",
|
|
data: {
|
|
name: NAME,
|
|
codeName: `${CODE_NAME_BASE}-${Date.now()}`,
|
|
approvalStatus: "approved",
|
|
category: "civilian",
|
|
description: { root: { type: "root", children: [{ type: "text", text: "E2E fixture" }] } },
|
|
materials: [{ resource: scrapId, amount: 1 }],
|
|
constructionDurationMinutes: 1,
|
|
terrainType: "land",
|
|
maxHealth: 100,
|
|
interiorEnabled: true,
|
|
interiorName: "E2E Interior",
|
|
interiorAccess: { mode: "anyone" },
|
|
rooms: [
|
|
{
|
|
key: "annex",
|
|
name: "Testing Annex",
|
|
roomType: "annex",
|
|
hotspot: { x: 10, y: 10, width: 30, height: 40 },
|
|
initialLevel: 0,
|
|
maxLevel: 1,
|
|
levels: [{ level: 1, label: "Opened up", upgradeDurationMinutes: 1 }],
|
|
decay: { conditionPerDay: 0, effectFloor: 0, junkMax: 1, initialJunkLevel: 1 },
|
|
junkLoot: [
|
|
{
|
|
kind: "resource" as const,
|
|
item: { relationTo: "resources" as const, value: scrapId },
|
|
amountMin: 3,
|
|
amountMax: 8,
|
|
weight: 1,
|
|
},
|
|
],
|
|
},
|
|
],
|
|
} as Record<string, unknown>,
|
|
draft: false,
|
|
overrideAccess: true,
|
|
});
|
|
|
|
const instance = await payload.create({
|
|
collection: "game-structures",
|
|
data: {
|
|
name: NAME,
|
|
type: blueprint.id as number,
|
|
constructionStatus: "complete",
|
|
},
|
|
draft: false,
|
|
overrideAccess: true,
|
|
});
|
|
instanceId = instance.id as number;
|
|
}
|
|
|
|
async function activeJob(roomKey: string, type: string): Promise<{ id: number; endsAt?: string; status?: string } | null> {
|
|
const res = await payload.find({
|
|
collection: "interior-jobs",
|
|
where: { structure: { equals: instanceId }, type: { equals: type } },
|
|
sort: "-createdAt",
|
|
limit: 1,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
const job = res.docs[0] as unknown as { id: number; endsAt?: string; status?: string } | undefined;
|
|
if (!job) return null;
|
|
const roomRes = await payload.find({
|
|
collection: "structure-rooms",
|
|
where: { structure: { equals: instanceId }, roomKey: { equals: roomKey } },
|
|
limit: 1,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
if (roomRes.totalDocs === 0) return null;
|
|
return job;
|
|
}
|
|
|
|
async function pollJobCompleted(jobId: number, timeoutMs: number): Promise<string> {
|
|
const deadline = Date.now() + timeoutMs;
|
|
for (;;) {
|
|
const job = (await payload.findByID({
|
|
collection: "interior-jobs",
|
|
id: jobId,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
})) as unknown as { status: string };
|
|
if (job.status !== "active") return job.status;
|
|
if (Date.now() > deadline) throw new Error(`job ${jobId} still active after ${timeoutMs}ms`);
|
|
await new Promise((r) => setTimeout(r, 2_000));
|
|
}
|
|
}
|
|
|
|
test.describe("Interior flow: enter -> open sealed room -> cleanup -> collect", () => {
|
|
test.setTimeout(420_000);
|
|
|
|
test.beforeAll(async () => {
|
|
await loadPayload();
|
|
scrapId = await ensureScrap();
|
|
await makeFixture();
|
|
});
|
|
|
|
test("member opens the annex, clears junk, and collects salvage through the UI", async ({ page }) => {
|
|
// Login (same seed as frontend.e2e.spec.ts).
|
|
await page.goto("/login");
|
|
await page.getByLabel("Username").fill("dev");
|
|
await page.getByLabel("Password").fill("Test123");
|
|
await page.getByRole("button", { name: "Log in" }).click();
|
|
await page.waitForURL((url) => !url.pathname.startsWith("/login"), { timeout: 60_000 });
|
|
|
|
// Interiors list -> our station card -> Enter interior.
|
|
await page.goto("/logistics/interiors", { timeout: 120_000 });
|
|
await expect(page.getByText(NAME).first()).toBeVisible({ timeout: 60_000 });
|
|
await page.getByRole("link", { name: "Enter interior" }).first().click();
|
|
await page.waitForURL(/\/logistics\/structures\/\d+\/interior/, { timeout: 60_000 });
|
|
|
|
// Floorplan: the annex is sealed; open the room sheet.
|
|
const annex = page.getByRole("button", { name: /^Testing Annex:/ });
|
|
await expect(annex).toBeVisible({ timeout: 60_000 });
|
|
await expect(annex).toHaveAttribute("aria-label", /Sealed/);
|
|
await annex.click();
|
|
|
|
// Open Room (Status tab default).
|
|
const openBtn = page.getByRole("button", { name: "Open Room" });
|
|
await expect(openBtn).toBeVisible({ timeout: 15_000 });
|
|
await openBtn.click();
|
|
|
|
// A 1-minute job should exist and be active.
|
|
let open = await activeJob("annex", "open");
|
|
if (!open) {
|
|
await page.waitForTimeout(4_000);
|
|
open = await activeJob("annex", "open");
|
|
}
|
|
expect(open?.id).toBeTruthy();
|
|
const openId = open!.id;
|
|
|
|
// Duration is ~1 minute real time; sweep only completes due jobs.
|
|
const openDeadline = Date.now() + 90_000;
|
|
for (;;) {
|
|
const job = (await payload.findByID({
|
|
collection: "interior-jobs",
|
|
id: openId,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
})) as unknown as { endsAt?: string };
|
|
if (job.endsAt && new Date(job.endsAt).getTime() <= Date.now()) break;
|
|
if (Date.now() > openDeadline) throw new Error("open job never reached its end time");
|
|
await page.waitForTimeout(3_000);
|
|
}
|
|
const completed = await sweepInteriorJobsNow();
|
|
expect(completed).toBeGreaterThanOrEqual(1);
|
|
expect(await pollJobCompleted(openId, 30_000)).toBe("awaiting_collect");
|
|
|
|
// Cleanup: collect the finished OPEN job first (one job per room slot),
|
|
// then start CLEANUP from the Jobs tab.
|
|
await page.reload({ timeout: 60_000 });
|
|
await page.getByRole("button", { name: /^Testing Annex:/ }).click();
|
|
await page.getByRole("tab", { name: "Jobs" }).click();
|
|
const collectOpen = page.getByRole("button", { name: "Collect" });
|
|
await expect(collectOpen).toBeVisible({ timeout: 15_000 });
|
|
await collectOpen.click();
|
|
await page.waitForTimeout(2_000);
|
|
await page.reload({ timeout: 60_000 });
|
|
await page.getByRole("button", { name: /^Testing Annex:/ }).click();
|
|
await page.getByRole("tab", { name: "Jobs" }).click();
|
|
|
|
const cleanBtn = page.getByRole("button", { name: "Start Cleanup" });
|
|
await expect(cleanBtn).toBeVisible({ timeout: 15_000 });
|
|
await cleanBtn.click();
|
|
|
|
let cleanup = await activeJob("annex", "cleanup");
|
|
if (!cleanup) {
|
|
await page.waitForTimeout(4_000);
|
|
cleanup = await activeJob("annex", "cleanup");
|
|
}
|
|
expect(cleanup?.id).toBeTruthy();
|
|
const cleanupId = cleanup!.id;
|
|
|
|
// Fast-forward the 15-minute cleanup window, then sweep it to completion.
|
|
await payload.update({
|
|
collection: "interior-jobs",
|
|
id: cleanupId,
|
|
overrideAccess: true,
|
|
data: { endsAt: new Date(Date.now() - 60_000).toISOString() },
|
|
} as never);
|
|
await sweepInteriorJobsNow();
|
|
expect(await pollJobCompleted(cleanupId, 30_000)).toBe("awaiting_collect");
|
|
|
|
// Collect: output credit lands in structure storage (scrap from loot roll).
|
|
await page.reload({ timeout: 60_000 });
|
|
await page.getByRole("button", { name: /^Testing Annex:/ }).click();
|
|
await page.getByRole("tab", { name: "Jobs" }).click();
|
|
const collectBtn = page.getByRole("button", { name: "Collect" });
|
|
await expect(collectBtn).toBeVisible({ timeout: 15_000 });
|
|
await collectBtn.click();
|
|
|
|
// The server-side job flips to collected and the store holds scrap.
|
|
await expect
|
|
.poll(
|
|
async () => {
|
|
const j = await payload.findByID({ collection: "interior-jobs", id: cleanupId, depth: 0, overrideAccess: true });
|
|
return (j as unknown as { status: string }).status;
|
|
},
|
|
{ timeout: 30_000 },
|
|
)
|
|
.toBe("collected");
|
|
const struct = (await payload.findByID({
|
|
collection: "game-structures",
|
|
id: instanceId,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
})) as unknown as { storedResources?: Array<{ resource: unknown; amount: number }> };
|
|
const scrapRow = (struct.storedResources ?? []).find(
|
|
(r) => (typeof r.resource === "object" && r.resource !== null ? (r.resource as { id: number }).id : r.resource) === scrapId,
|
|
);
|
|
expect(scrapRow?.amount ?? 0).toBeGreaterThanOrEqual(3);
|
|
});
|
|
|
|
test.afterAll(async () => {
|
|
if (!payload || !instanceId) return;
|
|
const jobs = await payload.find({
|
|
collection: "interior-jobs",
|
|
where: { structure: { equals: instanceId } },
|
|
limit: 50,
|
|
overrideAccess: true,
|
|
});
|
|
for (const j of jobs.docs) {
|
|
await payload.delete({ collection: "interior-jobs", id: j.id as number, overrideAccess: true }).catch(() => undefined);
|
|
}
|
|
const rooms = await payload.find({
|
|
collection: "structure-rooms",
|
|
where: { structure: { equals: instanceId } },
|
|
limit: 50,
|
|
overrideAccess: true,
|
|
});
|
|
for (const r of rooms.docs) {
|
|
await payload.delete({ collection: "structure-rooms", id: r.id as number, overrideAccess: true }).catch(() => undefined);
|
|
}
|
|
const inst = await payload.findByID({ collection: "game-structures", id: instanceId, depth: 0, overrideAccess: true }).catch(() => null);
|
|
if (inst) {
|
|
const bpId = typeof inst.type === "object" && inst.type !== null ? (inst.type as { id: number }).id : (inst.type as number);
|
|
await payload.delete({ collection: "game-structures", id: instanceId, overrideAccess: true }).catch(() => undefined);
|
|
if (bpId) await payload.delete({ collection: "structures", id: bpId, overrideAccess: true }).catch(() => undefined);
|
|
}
|
|
});
|
|
});
|