brackt/app/routes/__tests__/admin.sports-seasons.bracket.generate.test.ts
Claude 1e215c3ac9
All checks were successful
🚀 Deploy / 🧪 Test (pull_request) Successful in 3m14s
🚀 Deploy / ʦ🔍 Typecheck & Lint (pull_request) Successful in 1m18s
🚀 Deploy / 🐳 Build (pull_request) Has been skipped
🚀 Deploy / 🚀 Deploy (pull_request) Has been skipped
Fix three defects found reviewing the bracket entry-floor work
All three predate the EV fix on this branch and were surfaced by a review
of the full main..HEAD range.

1. reprocess-bracket skipped its wipe exactly when it was needed.

   The wipe was guarded on `completed.length > 0`, but clear-bracket
   deliberately leaves placements alone and tells the admin to "Run
   Reprocess Bracket after rebuilding to clear the placements those
   results produced". After clear then regenerate nothing is completed,
   so the wipe was skipped and the discarded bracket's finalized
   placements survived — and upsertParticipantResult's never-un-finalize
   guard then stopped the entry floors and the replay from correcting
   them. The advertised recovery path could not work.

   The guard was not arbitrary: seasonParticipantResults is keyed by
   sports season, not by event, so a season-wide delete takes every
   other event's placements with it. Rather than flip the condition,
   narrow the delete. New deleteParticipantResultsForParticipants scopes
   it to the participants the bracket actually holds, which removes the
   collateral damage the guard was defending against, so the delete can
   run unconditionally. The participant set was already being computed
   further down for the elimination pass; it is now built once and
   reused. The qualifying branch keeps its season-wide delete, which is
   deliberate and rebuilds via finalizeQualifyingPoints.

2. Banked entry floors could miss teamStandings.totalPoints.

   generate-bracket recalculated standings only when `toEliminate` was
   empty, assuming markEliminatedAndAnnounce covers every other case. It
   does not — it recalculates only when the event is non-qualifying AND
   somebody was *newly* eliminated, i.e. had no prior result row. So the
   second run of a generation (the first wrote 0 for every non-bracket
   participant) recalculated nowhere, and neither did a qualifying event
   with teams to eliminate. The floors never reached the standings.

   markEliminatedAndAnnounce now returns { markedCount, recalculated }
   and the caller drives off that fact instead of re-deriving it, which
   also covers the case where the announcement threw — the catch
   swallows the error, and a failed recalc is precisely when the
   fallback should run.

3. The NBA mobile pager fell back to index geometry.

   Its BracketTreePaginated was the only one of five call sites not
   forwarding feeders/template, so mobile rendered "TBD" where desktop
   rendered "Winner of ...".

Tests: reprocess wipes on a bracket with nothing played, stays scoped to
the bracket, dedupes and skips empty slots, and leaves the qualifying
path alone; generate recalculates in each of the four gaps above and
still does not double-recalculate; and the NBA layout gives its mobile
pane the same slot labels as desktop. Each was confirmed to fail against
the previous behavior.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EmUdy42Rpgx9qZTnpQwirz
2026-08-27 17:26:23 +00:00

203 lines
7.5 KiB
TypeScript

/**
* generate-bracket banks the floors a seeding guarantees before anyone plays (an AFL
* top-4 seed cannot finish below the 5th-6th tier). Those floors only reach
* teamStandings.totalPoints through a standings recalculation, so the action has to be
* sure one ran — markEliminatedAndAnnounce runs one for its Discord announcement in some
* cases but not others.
*/
import { beforeEach, describe, expect, it, vi } from "vitest";
import { generateBracketFromTemplate } from "~/models/playoff-match";
import {
findParticipantResultsBySportsSeasonId,
setParticipantResult,
} from "~/models/participant-result";
import {
applyBracketEntryFloors,
recalculateAffectedLeagues,
} from "~/models/scoring-calculator";
import { getScoringEventById, updateScoringEvent } from "~/models/scoring-event";
import { findParticipantsBySportsSeasonId } from "~/models/season-participant";
import { action } from "../admin.sports-seasons.$id.events.$eventId.bracket.server";
vi.mock("~/database/context", () => ({ database: vi.fn(() => ({})) }));
vi.mock("~/models/scoring-event", async (importOriginal) => ({
...(await importOriginal<object>()),
getScoringEventById: vi.fn(),
updateScoringEvent: vi.fn(),
isReadOnlySibling: vi.fn(() => false),
}));
vi.mock("~/models/playoff-match", async (importOriginal) => ({
...(await importOriginal<object>()),
generateBracketFromTemplate: vi.fn(),
}));
vi.mock("~/models/participant-result", async (importOriginal) => ({
...(await importOriginal<object>()),
findParticipantResultsBySportsSeasonId: vi.fn(),
setParticipantResult: vi.fn(),
}));
vi.mock("~/models/scoring-calculator", async (importOriginal) => ({
...(await importOriginal<object>()),
applyBracketEntryFloors: vi.fn(),
recalculateAffectedLeagues: vi.fn(),
}));
vi.mock("~/models/season-participant", async (importOriginal) => ({
...(await importOriginal<object>()),
findParticipantsBySportsSeasonId: vi.fn(),
}));
const params = { id: "season-1", eventId: "event-1" };
const EVENT = {
id: "event-1",
name: "AFL Finals",
sportsSeasonId: "season-1",
isQualifyingEvent: false,
bracketTemplateId: "afl_10",
};
/** afl_10 takes exactly 10 seeded participants. */
const SEEDED = Array.from({ length: 10 }, (_, i) => `seed-${i + 1}`);
function generateRequest(): Request {
const body = new FormData();
body.set("intent", "generate-bracket");
body.set("templateId", "afl_10");
SEEDED.forEach((id, i) => body.set(`participant${i}`, id));
return new Request("http://localhost/generate", { method: "POST", body });
}
const run = (request: Request) =>
(action as unknown as (args: { request: Request; params: typeof params }) => Promise<{
error?: string;
success?: string;
}>)({ request, params });
/**
* @param extras participants in the season beyond the 10 seeded into the bracket —
* these are the ones generate-bracket marks eliminated.
* @param withExistingResults ids that already carry a result row, so
* markEliminatedAndAnnounce treats them as not newly eliminated.
*/
function setSeason(extras: string[], withExistingResults: string[] = []) {
vi.mocked(findParticipantsBySportsSeasonId).mockResolvedValue(
[...SEEDED, ...extras].map((id) => ({ id })) as unknown as Awaited<
ReturnType<typeof findParticipantsBySportsSeasonId>
>
);
vi.mocked(findParticipantResultsBySportsSeasonId).mockResolvedValue(
withExistingResults.map((participantId) => ({ participantId })) as unknown as Awaited<
ReturnType<typeof findParticipantResultsBySportsSeasonId>
>
);
}
describe("generate-bracket entry-floor standings recalculation", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(getScoringEventById).mockResolvedValue(
EVENT as unknown as Awaited<ReturnType<typeof getScoringEventById>>
);
vi.mocked(generateBracketFromTemplate).mockResolvedValue(
undefined as unknown as Awaited<ReturnType<typeof generateBracketFromTemplate>>
);
vi.mocked(updateScoringEvent).mockResolvedValue(
undefined as unknown as Awaited<ReturnType<typeof updateScoringEvent>>
);
vi.mocked(setParticipantResult).mockResolvedValue(
undefined as unknown as Awaited<ReturnType<typeof setParticipantResult>>
);
vi.mocked(recalculateAffectedLeagues).mockResolvedValue(
undefined as unknown as Awaited<ReturnType<typeof recalculateAffectedLeagues>>
);
// afl_10 seeds 1-4 into the Qualifying Finals, whose entry floor is the 5th-6th tier.
vi.mocked(applyBracketEntryFloors).mockResolvedValue(4);
});
it("recalculates when every eliminated team already had a result row", async () => {
// The second run of a generation: the first wrote position 0 for the non-bracket
// participants, so nobody is *newly* eliminated and the announcement is skipped.
// The floors banked moments ago would never reach the standings.
setSeason(["extra-1"], ["extra-1"]);
const result = await run(generateRequest());
expect(result.success).toBeDefined();
expect(recalculateAffectedLeagues).toHaveBeenCalledTimes(1);
expect(recalculateAffectedLeagues).toHaveBeenCalledWith(
"season-1",
expect.anything(),
expect.objectContaining({ skipDiscord: true })
);
});
it("recalculates for a qualifying event, which never announces eliminations", async () => {
vi.mocked(getScoringEventById).mockResolvedValue(
{ ...EVENT, isQualifyingEvent: true } as unknown as Awaited<
ReturnType<typeof getScoringEventById>
>
);
setSeason(["extra-1"]);
await run(generateRequest());
expect(recalculateAffectedLeagues).toHaveBeenCalledTimes(1);
expect(recalculateAffectedLeagues).toHaveBeenCalledWith(
"season-1",
expect.anything(),
expect.objectContaining({ skipDiscord: true })
);
});
it("recalculates when the bracket field is the whole season", async () => {
setSeason([]);
await run(generateRequest());
expect(recalculateAffectedLeagues).toHaveBeenCalledTimes(1);
});
it("recalculates when the elimination announcement threw", async () => {
// The announcement is best-effort and its failure is swallowed — but a failed recalc
// is exactly when the floors still need one.
setSeason(["extra-1"]);
vi.mocked(recalculateAffectedLeagues)
.mockRejectedValueOnce(new Error("discord down"))
.mockResolvedValue(undefined as unknown as Awaited<ReturnType<typeof recalculateAffectedLeagues>>);
const result = await run(generateRequest());
expect(result.success).toBeDefined();
expect(recalculateAffectedLeagues).toHaveBeenCalledTimes(2);
expect(recalculateAffectedLeagues).toHaveBeenLastCalledWith(
"season-1",
expect.anything(),
expect.objectContaining({ skipDiscord: true })
);
});
it("does not recalculate twice when the announcement already did", async () => {
setSeason(["extra-1"]);
await run(generateRequest());
expect(recalculateAffectedLeagues).toHaveBeenCalledTimes(1);
// The announcing call, not the floor fallback.
expect(recalculateAffectedLeagues).toHaveBeenCalledWith(
"season-1",
expect.anything(),
expect.objectContaining({ eliminatedParticipantIds: ["extra-1"] })
);
});
it("does not recalculate at all when no floors were banked", async () => {
// A template that guarantees nothing at seeding: no floors, nobody to eliminate,
// so there is nothing for a recalculation to pick up.
vi.mocked(applyBracketEntryFloors).mockResolvedValue(0);
setSeason([]);
await run(generateRequest());
expect(recalculateAffectedLeagues).not.toHaveBeenCalled();
});
});