diff --git a/.codacy.yml b/.codacy.yml index f47d1e8..50f9e1c 100644 --- a/.codacy.yml +++ b/.codacy.yml @@ -5,3 +5,8 @@ engines: # Test suites use plain asserts by design (pytest); Bandit B101 flags # every one of them as a high-severity "assert used" finding. - "backend/tests/**" + biome: + exclude_paths: + # Playwright e2e specs trip Biome's Qwik-framework rules + # (useQwikValidLexicalScope), which do not apply to this React project. + - "frontend/tests/**" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9fe3acd..dfed687 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -93,3 +93,14 @@ jobs: DAL_PLAYWRIGHT_TEST_BACKEND: 1 working-directory: frontend run: npm run test:e2e + + - name: Upload Playwright report and traces on failure + if: failure() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # @v4.6.2 + with: + name: playwright-report + path: | + frontend/playwright-report + frontend/test-results + if-no-files-found: ignore + retention-days: 7 diff --git a/README.md b/README.md index 5143e8c..7e4de97 100644 --- a/README.md +++ b/README.md @@ -453,7 +453,7 @@ uv run --no-sync pytest # uses a fake dal module (no C++ build needed) cd frontend npm run build # type-check + production build npm test # vitest unit tests (jsdom; no browser or backend needed) -npm run test:e2e # Playwright smoke tests (starts/stops the web UI) +npm run test:e2e # Playwright browser tests (starts/stops the web UI) ``` The vitest unit suite under `frontend/tests/unit/` covers the API client, the @@ -461,6 +461,13 @@ valuation panel, model-form parsing, formatting helpers, and Curve Lab visual and API state. It runs in jsdom against mocked API responses, needs neither a browser nor a backend, and also runs in the frontend CI job. +The e2e suite under `frontend/tests/e2e/` covers the primary browser flows: +navigation and the dashboard, trade/portfolio valuation lifecycles, CRUD and +delete guards for products/models/trades/portfolios, product-builder +templates and debug dumps, curve calibration runs, and the Curve Lab +workspace. The CI e2e job uploads the Playwright report and traces as a +workflow artifact when the suite fails. + The default Playwright command uses the native-only application startup path. CI uses an explicit canned DAL test double while retaining the real FastAPI routers and Vite frontend: diff --git a/frontend/tests/e2e/dashboard.spec.ts b/frontend/tests/e2e/dashboard.spec.ts new file mode 100644 index 0000000..ce036bc --- /dev/null +++ b/frontend/tests/e2e/dashboard.spec.ts @@ -0,0 +1,225 @@ +import { expect, test, type Page } from "@playwright/test"; + +// The app formats numbers via toLocaleString(undefined, ...); derive expected +// text instead of hard-coding en-US separators. +const money = (value: number) => + new Intl.NumberFormat(undefined, { maximumFractionDigits: 2 }).format(value); + +// valuation.spec.ts runs on a parallel worker against the same in-memory +// store and asserts on the NEWEST valuation run (`.first()`), snapshotted +// right after its own 1024-path run completes. A run of ours created between +// its run and its /valuations snapshot would take that slot. Its run requires +// a trade named "E2E trade" created through the UI first, so: +// - no "E2E trade" trade yet -> its run cannot exist; ours will be older; +// - otherwise wait until its 1024-path run has settled and its snapshot +// window (a few seconds after completion) has closed. +async function dodgeValuationSpecWindow(page: Page) { + const tradesResp = await page.request.get("/api/trades"); + const trades = (await tradesResp.json()) as { name: string }[]; + if (!trades.some((t) => t.name === "E2E trade")) return; + + const listRuns = async () => { + const resp = await page.request.get("/api/valuations"); + return (await resp.json()) as { + status: string; + config: { num_paths: number }; + }[]; + }; + await expect + .poll( + async () => + (await listRuns()).find((r) => r.config.num_paths === 1024)?.status, + { timeout: 60_000 } + ) + .toBe("completed"); + await page.waitForTimeout(5_000); +} + +// Seeds product + model + trade via the API, prices the trade, and polls until +// the canned backend settles the run. Returns the valuation id. +async function seedCompletedTradeValuation( + page: Page, + tradeName: string, + notional: number +): Promise { + const productResp = await page.request.post("/api/products", { + data: { + name: `${tradeName} Product`, + description: "", + template: null, + rows: [ + { date_kind: "label", label: "STRIKE", event: "120.00" }, + { + date_kind: "date", + date: "2025-09-15", + event: "call pays MAX(spot() - STRIKE, 0.0)", + }, + ], + }, + }); + expect(productResp.status()).toBe(201); + const product = (await productResp.json()) as { id: string }; + + const modelResp = await page.request.post("/api/models", { + data: { + name: `${tradeName} Model`, + kind: "BSModelData_", + bs: { spot: 100, vol: 0.2, rate: 0.0, div: 0.0 }, + }, + }); + expect(modelResp.status()).toBe(201); + const model = (await modelResp.json()) as { id: string }; + + const tradeResp = await page.request.post("/api/trades", { + data: { + name: tradeName, + book: "EQ-EXOTICS", + counterparty: "", + notional, + quantity: 1, + product_id: product.id, + model_id: model.id, + }, + }); + expect(tradeResp.status()).toBe(201); + const trade = (await tradeResp.json()) as { id: string }; + + await dodgeValuationSpecWindow(page); + const valueResp = await page.request.post(`/api/trades/${trade.id}/value`, { + data: { + num_paths: 512, + method: "sobol", + use_brownian_bridge: false, + enable_aad: true, + smooth: 0.01, + evaluation_date: "2022-09-15", + }, + }); + expect(valueResp.status()).toBe(200); + const pending = (await valueResp.json()) as { id: string }; + await expect + .poll( + async () => { + const resp = await page.request.get(`/api/valuations/${pending.id}`); + return ((await resp.json()) as { status: string }).status; + }, + { timeout: 15_000 } + ) + .toBe("completed"); + return pending.id; +} + +test("dashboard renders entity counts and recent valuation runs", async ({ + page, +}) => { + test.skip( + process.env.DAL_PLAYWRIGHT_TEST_BACKEND !== "1", + "Only applies to the explicit Playwright test backend" + ); + + const portfolioResp = await page.request.post("/api/portfolios", { + data: { name: "E2E Dash Portfolio", description: "" }, + }); + expect(portfolioResp.status()).toBe(201); + // Canned unit PV is 8.0; notional 777,000 keeps this run's PV unique. + await seedCompletedTradeValuation(page, "E2E Dash Trade", 777_000); + + await page.goto("/"); + await expect(page.getByRole("heading", { name: "Dashboard" })).toBeVisible(); + + // The store is shared across the run, so counts are lower bounds only. + const cardMetric = async (label: string) => { + const card = page.locator(".card").filter({ + has: page.getByRole("heading", { name: label, exact: true }), + }); + return Number(await card.locator(".metric").textContent()); + }; + await expect(async () => { + expect(await cardMetric("Portfolios")).toBeGreaterThanOrEqual(1); + expect(await cardMetric("Trades")).toBeGreaterThanOrEqual(1); + expect(await cardMetric("Valuation Runs")).toBeGreaterThanOrEqual(1); + }).toPass(); + + const runRow = page + .getByRole("row") + .filter({ hasText: money(8 * 777_000) }); + await expect(runRow).toBeVisible(); + await expect(runRow).toContainText("trade"); + await expect(runRow).toContainText("canned-dal (stub)"); +}); + +test("valuations page lists runs, badges status and expands details", async ({ + page, +}) => { + test.skip( + process.env.DAL_PLAYWRIGHT_TEST_BACKEND !== "1", + "Only applies to the explicit Playwright test backend" + ); + + // Notional 888,000 keeps this run's PV distinct from any sibling test. + await seedCompletedTradeValuation(page, "E2E Badge Trade", 888_000); + + // The canned backend never produces a failed run on its own (per-trade + // failures still settle as "completed"), so prepend a synthetic failed run + // to the real list response for badge/error evidence. + const failedRun = { + id: "f".repeat(32), + target_kind: "trade", + target_id: "0".repeat(32), + backend: "canned-dal", + is_native: false, + config: { + num_paths: 128, + method: "sobol", + use_brownian_bridge: false, + enable_aad: false, + smooth: 0.01, + evaluation_date: null, + }, + total_pv: 0, + total_greeks: {}, + trades: [], + created_at: "2026-01-02T00:00:00Z", + status: "failed", + error_message: "synthetic failure for badge evidence", + }; + await page.route("**/api/valuations", async (route) => { + const response = await route.fetch(); + const runs = (await response.json()) as unknown[]; + await route.fulfill({ + response, + contentType: "application/json", + body: JSON.stringify([failedRun, ...runs]), + }); + }); + + await page.goto("/valuations"); + await expect( + page.getByRole("heading", { name: "Valuation Runs" }) + ).toBeVisible(); + + const completedRow = page + .getByRole("row") + .filter({ hasText: money(8 * 888_000) }); + await expect(completedRow).toBeVisible(); + await expect(completedRow).toContainText("trade"); + await expect(completedRow).toContainText("completed"); + await expect(completedRow).toContainText("canned-dal (stub)"); + + await completedRow.getByRole("button", { name: "Details" }).click(); + await expect(page.getByRole("heading", { name: "Greeks" })).toBeVisible(); + await expect(page.getByText(/d_spot:/)).toBeVisible(); + await expect( + page.getByRole("cell", { name: "E2E Badge Trade", exact: true }) + ).toBeVisible(); + + const failedRow = page.getByRole("row").filter({ hasText: "failed" }); + await expect(failedRow).toHaveCount(1); + await failedRow.getByRole("button", { name: "Details" }).click(); + await expect(page.getByRole("heading", { name: "Error" })).toBeVisible(); + await expect(page.getByText("synthetic failure for badge evidence")).toBeVisible(); + + // The dashboard flags the failed run inline in its recent-activity table. + await page.goto("/"); + await expect(page.getByText("(failed)")).toBeVisible(); +}); diff --git a/frontend/tests/e2e/models.spec.ts b/frontend/tests/e2e/models.spec.ts new file mode 100644 index 0000000..e9b99b8 --- /dev/null +++ b/frontend/tests/e2e/models.spec.ts @@ -0,0 +1,165 @@ +import { expect, test } from "@playwright/test"; + +// fmtNum renders with a fixed fraction count; derive expected text instead of +// hard-coding en-US separators. +const num = (value: number, digits: number) => + value.toLocaleString(undefined, { + minimumFractionDigits: digits, + maximumFractionDigits: digits, + }); + +test("creates, updates and deletes a Black-Scholes model", async ({ page }) => { + test.skip( + process.env.DAL_PLAYWRIGHT_TEST_BACKEND !== "1", + "Only applies to the explicit Playwright test backend" + ); + + page.on("dialog", (dialog) => { + void dialog.accept(); + }); + + await page.goto("/models"); + await page.locator("#model-name").fill("E2E Alpha Model"); + await page.locator("#model-vol").fill("0.2"); + await page.getByRole("button", { name: "Create model" }).click(); + + const createdRow = page.getByRole("row").filter({ hasText: "E2E Alpha Model" }); + await expect(createdRow).toBeVisible(); + await expect(createdRow).toContainText("BSModelData_"); + await expect(createdRow).toContainText(num(0.2, 4)); + + // The Models page has no inline editor; the update path is PUT /api/models/{id}. + // Drive it through the request context and verify the UI reflects the merge. + const modelsResp = await page.request.get("/api/models"); + const models = (await modelsResp.json()) as { id: string; name: string }[]; + const modelId = models.find((m) => m.name === "E2E Alpha Model")?.id; + expect(modelId).toBeTruthy(); + + const updateResp = await page.request.put(`/api/models/${modelId}`, { + data: { + name: "E2E Beta Model", + bs: { spot: 100, vol: 0.35, rate: 0.01, div: 0.0 }, + }, + }); + expect(updateResp.ok()).toBeTruthy(); + + await page.reload(); + const updatedRow = page + .getByRole("row") + .filter({ hasText: "E2E Beta Model" }); + await expect(updatedRow).toBeVisible(); + await expect(updatedRow).toContainText("BSModelData_"); + await expect(updatedRow).toContainText(num(0.35, 4)); + await expect(updatedRow).toContainText(num(0.01, 4)); + await expect( + page.getByRole("row").filter({ hasText: "E2E Alpha Model" }) + ).toHaveCount(0); + + await updatedRow.getByRole("button", { name: "Delete" }).click(); + await expect( + page.getByRole("row").filter({ hasText: "E2E Beta Model" }) + ).toHaveCount(0); +}); + +test("rejects a Dupire surface whose vols do not match spots x times", async ({ + page, +}) => { + test.skip( + process.env.DAL_PLAYWRIGHT_TEST_BACKEND !== "1", + "Only applies to the explicit Playwright test backend" + ); + + await page.goto("/models"); + await page.locator("#model-kind").selectOption("DupireModelData_"); + await page.locator("#model-name").fill("E2E Broken Dupire"); + // Default vols are a 3x3 matrix against three spot strikes; shrinking the + // times axis to two entries makes the surface non-rectangular. + await page.locator("#dupire-times").fill("0.25, 0.5"); + await page.getByRole("button", { name: "Create model" }).click(); + + const banner = page.locator("div.error"); + await expect(banner).toContainText("422"); + await expect(banner).toContainText( + "Dupire vols must be a rectangular matrix matching spots x times" + ); + await expect( + page.getByRole("row").filter({ hasText: "E2E Broken Dupire" }) + ).toHaveCount(0); +}); + +test("model delete is guarded while a trade references it", async ({ + page, +}) => { + test.skip( + process.env.DAL_PLAYWRIGHT_TEST_BACKEND !== "1", + "Only applies to the explicit Playwright test backend" + ); + + const productResp = await page.request.post("/api/products", { + data: { + name: "E2E ModelGuard Product", + description: "", + template: null, + rows: [ + { date_kind: "label", label: "STRIKE", event: "120.00" }, + { + date_kind: "date", + date: "2025-09-15", + event: "call pays MAX(spot() - STRIKE, 0.0)", + }, + ], + }, + }); + expect(productResp.status()).toBe(201); + const product = (await productResp.json()) as { id: string }; + + const modelResp = await page.request.post("/api/models", { + data: { + name: "E2E Guarded Model", + kind: "BSModelData_", + bs: { spot: 100, vol: 0.2, rate: 0.0, div: 0.0 }, + }, + }); + expect(modelResp.status()).toBe(201); + const model = (await modelResp.json()) as { id: string }; + + const tradeResp = await page.request.post("/api/trades", { + data: { + name: "E2E ModelGuard Trade", + book: "EQ-EXOTICS", + counterparty: "", + notional: 1, + quantity: 1, + product_id: product.id, + model_id: model.id, + }, + }); + expect(tradeResp.status()).toBe(201); + const trade = (await tradeResp.json()) as { id: string }; + + page.on("dialog", (dialog) => { + void dialog.accept(); + }); + + // Deleting the referenced model is rejected with a 409 naming the trade. + await page.goto("/models"); + const modelRow = page + .getByRole("row") + .filter({ hasText: "E2E Guarded Model" }); + await expect(modelRow).toBeVisible(); + await modelRow.getByRole("button", { name: "Delete" }).click(); + + const banner = page.locator("div.error"); + await expect(banner).toContainText("409"); + await expect(banner).toContainText("Cannot delete model"); + await expect(banner).toContainText(`still referenced by trade ${trade.id}`); + await expect(modelRow).toBeVisible(); + + // Once the referencing trade is gone the delete succeeds. + const deleteResp = await page.request.delete(`/api/trades/${trade.id}`); + expect(deleteResp.status()).toBe(204); + await modelRow.getByRole("button", { name: "Delete" }).click(); + await expect( + page.getByRole("row").filter({ hasText: "E2E Guarded Model" }) + ).toHaveCount(0); +}); diff --git a/frontend/tests/e2e/portfolios.spec.ts b/frontend/tests/e2e/portfolios.spec.ts new file mode 100644 index 0000000..65d57e8 --- /dev/null +++ b/frontend/tests/e2e/portfolios.spec.ts @@ -0,0 +1,183 @@ +import { expect, test } from "@playwright/test"; + +// The app formats numbers via toLocaleString(undefined, ...); derive expected +// text instead of hard-coding en-US separators. +const money = (value: number) => + new Intl.NumberFormat(undefined, { maximumFractionDigits: 2 }).format(value); + +const NOTIONAL = 1_500_000; +// Canned backend prices every trade at unit PV 8.0, scaled by notional x quantity. +const TOTAL_PV_TEXT = money(8 * NOTIONAL); +const PATH_COUNT_TEXT = (2048).toLocaleString(); + +// valuation.spec.ts runs on a parallel worker against the same in-memory +// store and asserts on the NEWEST valuation run (`.first()`), snapshotted +// right after its own 1024-path run completes. A run of ours created between +// its run and its /valuations snapshot would take that slot. Its run requires +// a trade named "E2E trade" created through the UI first, so: +// - no "E2E trade" trade yet -> its run cannot exist; ours will be older; +// - otherwise wait until its 1024-path run has settled and its snapshot +// window (a few seconds after completion) has closed. +async function dodgeValuationSpecWindow(page: import("@playwright/test").Page) { + const tradesResp = await page.request.get("/api/trades"); + const trades = (await tradesResp.json()) as { name: string }[]; + if (!trades.some((t) => t.name === "E2E trade")) return; + + const listRuns = async () => { + const resp = await page.request.get("/api/valuations"); + return (await resp.json()) as { + status: string; + config: { num_paths: number }; + }[]; + }; + await expect + .poll( + async () => + (await listRuns()).find((r) => r.config.num_paths === 1024)?.status, + { timeout: 60_000 } + ) + .toBe("completed"); + await page.waitForTimeout(5_000); +} + +async function seedTrade(page: import("@playwright/test").Page) { + const productResp = await page.request.post("/api/products", { + data: { + name: "E2E PF Product", + description: "", + template: null, + rows: [ + { date_kind: "label", label: "STRIKE", event: "120.00" }, + { + date_kind: "date", + date: "2025-09-15", + event: "call pays MAX(spot() - STRIKE, 0.0)", + }, + ], + }, + }); + expect(productResp.status()).toBe(201); + const product = (await productResp.json()) as { id: string }; + + const modelResp = await page.request.post("/api/models", { + data: { + name: "E2E PF Model", + kind: "BSModelData_", + bs: { spot: 100, vol: 0.2, rate: 0.0, div: 0.0 }, + }, + }); + expect(modelResp.status()).toBe(201); + const model = (await modelResp.json()) as { id: string }; + + const tradeResp = await page.request.post("/api/trades", { + data: { + name: "E2E PF Trade", + book: "EQ-EXOTICS", + counterparty: "", + notional: NOTIONAL, + quantity: 1, + product_id: product.id, + model_id: model.id, + }, + }); + expect(tradeResp.status()).toBe(201); +} + +test("portfolio lifecycle: create, add trade, price, remove trade, delete", async ({ + page, +}) => { + test.skip( + process.env.DAL_PLAYWRIGHT_TEST_BACKEND !== "1", + "Only applies to the explicit Playwright test backend" + ); + + await seedTrade(page); + + // Deletion and removal go through window.confirm; accept every dialog. + page.on("dialog", (dialog) => { + void dialog.accept(); + }); + + await page.goto("/portfolios"); + await expect(page.getByRole("heading", { name: "Portfolios" })).toBeVisible(); + + // Create the portfolio via the Books panel form. + await page.getByRole("textbox").fill("E2E Portfolio Alpha"); + await page.getByRole("button", { name: "Create" }).click(); + const bookRow = page.getByRole("row").filter({ hasText: "E2E Portfolio Alpha" }); + await expect(bookRow).toBeVisible(); + await expect(bookRow.locator("td").nth(2)).toHaveText("0"); + + // Open it and add the seeded trade through the picker. + await bookRow.getByRole("button", { name: "Open" }).click(); + await expect( + page.getByRole("heading", { name: "E2E Portfolio Alpha", exact: true }) + ).toBeVisible(); + await page + .locator("select") + .filter({ hasText: "pick a trade" }) + .selectOption({ label: "E2E PF Trade" }); + await page.getByRole("button", { name: "Add trade" }).click(); + + const memberRow = page.getByRole("row").filter({ hasText: "E2E PF Trade" }); + await expect(memberRow).toBeVisible(); + await expect(memberRow).toContainText(money(NOTIONAL)); + await expect(bookRow.locator("td").nth(2)).toHaveText("1"); + + // Price the portfolio through its ValuationPanel; canned PV is 8 x notional. + await expect( + page.getByRole("heading", { name: "Price portfolio: E2E Portfolio Alpha" }) + ).toBeVisible(); + await page.getByLabel("Number of paths").fill("2048"); + await dodgeValuationSpecWindow(page); + await page.getByRole("button", { name: "Run valuation" }).click(); + await expect(page.getByText("Total PV")).toBeVisible({ timeout: 15_000 }); + await expect(page.getByText(TOTAL_PV_TEXT)).toBeVisible(); + await expect(page.getByRole("heading", { name: "d_spot" })).toBeVisible(); + + // The settled run lands on /valuations with target kind portfolio. + await page.goto("/valuations"); + const runRow = page + .getByRole("row") + .filter({ hasText: "portfolio" }) + .filter({ hasText: TOTAL_PV_TEXT }); + await expect(runRow).toContainText("completed"); + await expect(runRow).toContainText("canned-dal"); + await expect(runRow).toContainText(PATH_COUNT_TEXT); + + // Remove the trade (confirmation flow) and the member table empties. + await page.goto("/portfolios"); + await page + .getByRole("row") + .filter({ hasText: "E2E Portfolio Alpha" }) + .getByRole("button", { name: "Open" }) + .click(); + await page + .getByRole("row") + .filter({ hasText: "E2E PF Trade" }) + .getByRole("button", { name: "Remove" }) + .click(); + await expect( + page.getByRole("row").filter({ hasText: "E2E PF Trade" }) + ).toHaveCount(0); + await expect( + page + .getByRole("row") + .filter({ hasText: "E2E Portfolio Alpha" }) + .locator("td") + .nth(2) + ).toHaveText("0"); + + // Delete the portfolio (confirmation flow); the selector resets. + await page + .getByRole("row") + .filter({ hasText: "E2E Portfolio Alpha" }) + .getByRole("button", { name: "Delete" }) + .click(); + await expect( + page.getByRole("row").filter({ hasText: "E2E Portfolio Alpha" }) + ).toHaveCount(0); + await expect( + page.getByRole("heading", { name: "Select a portfolio" }) + ).toBeVisible(); +}); diff --git a/frontend/tests/e2e/product_builder.spec.ts b/frontend/tests/e2e/product_builder.spec.ts new file mode 100644 index 0000000..fcac31d --- /dev/null +++ b/frontend/tests/e2e/product_builder.spec.ts @@ -0,0 +1,71 @@ +import { expect, test } from "@playwright/test"; + +// The builder toolbar renders one ghost button per template, labelled with the +// template name from GET /api/products/templates. +const TEMPLATES = [ + { name: "European Call", rows: 2 }, + { name: "Up-and-Out Call", rows: 5 }, + { name: "Snowball", rows: 7 }, +]; + +test("loads every builder template into the editor", async ({ page }) => { + test.skip( + process.env.DAL_PLAYWRIGHT_TEST_BACKEND !== "1", + "Only applies to the explicit Playwright test backend" + ); + + await page.goto("/products"); + await expect(page.getByRole("heading", { name: "Product Builder" })).toBeVisible(); + + for (const template of TEMPLATES) { + await page.getByRole("button", { name: template.name }).click(); + await expect(page.locator("#product-name")).toHaveValue(template.name); + await expect(page.getByPlaceholder(/event script/)).toHaveCount( + template.rows + ); + } +}); + +test("debugs, saves and reloads a scripted product", async ({ page }) => { + test.skip( + process.env.DAL_PLAYWRIGHT_TEST_BACKEND !== "1", + "Only applies to the explicit Playwright test backend" + ); + + await page.goto("/products"); + await page.getByRole("button", { name: "European Call" }).click(); + await page.locator("#product-name").fill("E2E Builder Roundtrip"); + + // Render the rows through the canned Product_New / Product_Debug dump. + await page.getByRole("button", { name: "Debug (DAL)" }).click(); + const debug = page.locator("pre.debug"); + await expect(debug).toContainText("STRIKE"); + await expect(debug).toContainText("call pays MAX(spot() - STRIKE, 0.0)"); + + await page.getByRole("button", { name: "Save product" }).click(); + const savedRow = page + .getByRole("row") + .filter({ hasText: "E2E Builder Roundtrip" }); + await expect(savedRow).toBeVisible(); + // Name / description / # rows columns. + await expect(savedRow.locator("td").nth(2)).toHaveText("2"); + + // Dirty the editor with a different template, then load the saved product + // back: the schedule must round-trip exactly. + await page.getByRole("button", { name: "Snowball" }).click(); + await expect(page.getByPlaceholder(/event script/)).toHaveCount(7); + + await savedRow.getByRole("button", { name: "Load" }).click(); + await expect(page.locator("#product-name")).toHaveValue( + "E2E Builder Roundtrip" + ); + await expect(page.getByPlaceholder(/event script/)).toHaveCount(2); + await expect(page.getByPlaceholder(/STRIKE or START/)).toHaveValue("STRIKE"); + await expect(page.getByPlaceholder(/event script/).first()).toHaveValue( + "120.00" + ); + await expect(page.getByPlaceholder(/event script/).nth(1)).toHaveValue( + "call pays MAX(spot() - STRIKE, 0.0)" + ); + await expect(page.locator('input[type="date"]')).toHaveValue("2025-09-15"); +}); diff --git a/frontend/tests/e2e/trades.spec.ts b/frontend/tests/e2e/trades.spec.ts new file mode 100644 index 0000000..f1e0347 --- /dev/null +++ b/frontend/tests/e2e/trades.spec.ts @@ -0,0 +1,164 @@ +import { expect, test, type Page } from "@playwright/test"; + +// The app formats notionals via toLocaleString(undefined, ...); derive +// expected text instead of hard-coding en-US separators. +const money = (value: number) => + new Intl.NumberFormat(undefined, { maximumFractionDigits: 2 }).format(value); + +async function seedProductAndModel( + page: Page, + names: { product: string; model: string } +) { + const productResp = await page.request.post("/api/products", { + data: { + name: names.product, + description: "", + template: null, + rows: [ + { date_kind: "label", label: "STRIKE", event: "120.00" }, + { + date_kind: "date", + date: "2025-09-15", + event: "call pays MAX(spot() - STRIKE, 0.0)", + }, + ], + }, + }); + expect(productResp.status()).toBe(201); + const product = (await productResp.json()) as { id: string }; + + const modelResp = await page.request.post("/api/models", { + data: { + name: names.model, + kind: "BSModelData_", + bs: { spot: 100, vol: 0.2, rate: 0.0, div: 0.0 }, + }, + }); + expect(modelResp.status()).toBe(201); + const model = (await modelResp.json()) as { id: string }; + + return { productId: product.id, modelId: model.id }; +} + +test("creates, updates and deletes a trade", async ({ page }) => { + test.skip( + process.env.DAL_PLAYWRIGHT_TEST_BACKEND !== "1", + "Only applies to the explicit Playwright test backend" + ); + + await seedProductAndModel(page, { + product: "E2E Ticket Product", + model: "E2E Ticket Model", + }); + + // Deletion goes through window.confirm; accept every dialog. + page.on("dialog", (dialog) => { + void dialog.accept(); + }); + + await page.goto("/trades"); + await page.locator("#trade-name").fill("E2E Ticket Alpha"); + await page.locator("#trade-product").selectOption({ label: "E2E Ticket Product" }); + await page.locator("#trade-model").selectOption({ label: "E2E Ticket Model" }); + await page.locator("#trade-notional").fill("2000000"); + await page.getByRole("button", { name: "Create" }).click(); + + const createdRow = page.getByRole("row").filter({ hasText: "E2E Ticket Alpha" }); + await expect(createdRow).toBeVisible(); + await expect(createdRow).toContainText("E2E Ticket Product"); + await expect(createdRow).toContainText("E2E Ticket Model"); + await expect(createdRow).toContainText(money(2_000_000)); + + // The Trades page has no inline editor; the update path is PUT /api/trades/{id}. + // Drive it through the request context and verify the UI reflects the merge. + const tradesResp = await page.request.get("/api/trades"); + const trades = (await tradesResp.json()) as { id: string; name: string }[]; + const tradeId = trades.find((t) => t.name === "E2E Ticket Alpha")?.id; + expect(tradeId).toBeTruthy(); + + const updateResp = await page.request.put(`/api/trades/${tradeId}`, { + data: { name: "E2E Ticket Beta", notional: 3_500_000 }, + }); + expect(updateResp.ok()).toBeTruthy(); + + await page.reload(); + const renamedRow = page + .getByRole("row") + .filter({ hasText: "E2E Ticket Beta" }); + await expect(renamedRow).toBeVisible(); + await expect(renamedRow).toContainText(money(3_500_000)); + // Untouched fields survive the partial update. + await expect(renamedRow).toContainText("E2E Ticket Product"); + await expect( + page.getByRole("row").filter({ hasText: "E2E Ticket Alpha" }) + ).toHaveCount(0); + + await renamedRow.getByRole("button", { name: "Delete" }).click(); + await expect( + page.getByRole("row").filter({ hasText: "E2E Ticket Beta" }) + ).toHaveCount(0); +}); + +test("product delete is guarded while a trade references it", async ({ + page, +}) => { + test.skip( + process.env.DAL_PLAYWRIGHT_TEST_BACKEND !== "1", + "Only applies to the explicit Playwright test backend" + ); + + const { productId, modelId } = await seedProductAndModel(page, { + product: "E2E Guard Product", + model: "E2E Guard Model", + }); + const tradeResp = await page.request.post("/api/trades", { + data: { + name: "E2E Guard Trade", + book: "EQ-EXOTICS", + counterparty: "", + notional: 1, + quantity: 1, + product_id: productId, + model_id: modelId, + }, + }); + expect(tradeResp.status()).toBe(201); + const trade = (await tradeResp.json()) as { id: string }; + + page.on("dialog", (dialog) => { + void dialog.accept(); + }); + + // Deleting the referenced product is rejected with a 409 naming the trade. + await page.goto("/products"); + const productRow = page + .getByRole("row") + .filter({ hasText: "E2E Guard Product" }); + await expect(productRow).toBeVisible(); + await productRow.getByRole("button", { name: "Delete" }).click(); + + const banner = page.locator("div.error"); + await expect(banner).toContainText("409"); + await expect(banner).toContainText("Cannot delete product"); + await expect(banner).toContainText(`still referenced by trade ${trade.id}`); + await expect(productRow).toBeVisible(); + + // Remove the referencing trade through its own delete flow. + await page.goto("/trades"); + const tradeRow = page.getByRole("row").filter({ hasText: "E2E Guard Trade" }); + await tradeRow.getByRole("button", { name: "Delete" }).click(); + await expect( + page.getByRole("row").filter({ hasText: "E2E Guard Trade" }) + ).toHaveCount(0); + + // The product delete now succeeds. + await page.goto("/products"); + await page + .getByRole("row") + .filter({ hasText: "E2E Guard Product" }) + .getByRole("button", { name: "Delete" }) + .click(); + await expect( + page.getByRole("row").filter({ hasText: "E2E Guard Product" }) + ).toHaveCount(0); +});