brackt/app/models/team-score-events.ts

259 lines
8.3 KiB
TypeScript
Raw Normal View History

New design (#309) * Redesign home page with new layout and component system - Two-column layout (My Leagues 2/3, Upcoming Events 1/3) with mobile stack - LeagueRow: square avatar, gradient draft highlight, rank/points display, progress bar - MyLeaguesCard, CreateLeagueCard with shared SectionCardHeader - UpcomingEventsCard: vertical timeline with grouped multi-league events - Shared gradient system: BracktGradients SVG defs, GradientIcon wrapper, brand.ts constants - Button default variant updated to green→cyan gradient - Navbar: plain nav links with gradient hover, support/admin icon buttons - Accessibility fixes: semantic h2 headings, aria-label on LeagueAvatar and nav elements - Storybook stories for all new components Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Responsive league row layout and mobile polish - League rows stack avatar+name on top, stats full-width below on mobile - Stats spread to right side on sm+ screens with border separator on mobile - Tighter padding on mobile (px-3/py-3), full padding on sm+ - Card headers and content use px-3 sm:px-6 to reduce mobile gutters - Two-column home layout deferred to lg breakpoint (tablet gets stacked) - Active leagues sorted by completion percentage descending - Default rank 1 / 0 points for active leagues with no scoring events yet - Fix ordinal bug for 11th/12th/13th; add aria-labels to rank change indicators - Remove dead StatDivider className prop Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Improve claude file. * Add StandingsPreview card component with podium row styling - New StandingsPreview component with gold/silver/bronze row tints for top 3, team avatar, and LeagueRow-style stat columns (Ranking + Points) with rank and 7-day point change indicators - Fix GradientIcon in Storybook by adding BracktGradients decorator to preview.tsx (renamed from .ts to support JSX) - Fix degenerate SVG gradient on horizontal strokes by switching BracktGradients to gradientUnits="userSpaceOnUse" with Lucide-space coordinates (0→24) - Revert erroneous fill: url(#gradient) from GradientIcon; stroke-only fix was sufficient once gradientUnits was corrected Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Update components on league homepage. * Finish up league page styling. * Work on standings page. * Add story for RecentScoresCard * Update Point Progression Chart. * Sort point progression legend by ranking and add team links to standings rows * Fix standings discrepancy on change. * Create draft cell component. * Update draft board page * Draft room improvements. * Update some draft room styling. * Fix context menu missing. * Move tab navigation and autodraft to header row, narrow sidebar * Virtualize available participants list, memoize draft room props Adds @tanstack/react-virtual to replace separate mobile/desktop lists with a single unified virtual scroll loop. Also memoizes miniDraftGrid and availableParticipantsSectionProps, and switches pick lookup from Array.find to a Map for O(1) access. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Update draft room UI. * More draft room fixes. * Draft room tweaks. * Fix Rosters page. * Queue Section fixes. * Mobile Draft fixes. * Fix draft board page. * Create bracket look. * Bracket work. * Finish bracket page. * Homepage initial styling * homepage copy * Add privacy policy. Fixes #88. * how to play copy * rules copy * Fix brackets on homepage. * Add footer to website. * Glow on dots. * Landing page copy. * Fix sidebar. --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 13:14:55 -07:00
import { database } from "~/database/context";
import * as schema from "~/database/schema";
import { eq, inArray, desc, sql, and } from "drizzle-orm";
import { calculateBracketPoints, type ScoringRules } from "~/models/scoring-rules";
import { logger } from "~/lib/logger";
/**
* Low-level primitive: writes one team_score_events row with an explicit pointsDelta.
* participantIds are captured at write time so attribution is accurate regardless
* of future match results.
*
* When matchId is provided (bracket sports), one row is written per match using
* a partial unique index on (teamId, seasonId, matchId). When matchId is absent
* (non-bracket fallback), one row per (teamId, seasonId, scoringEventId) is used.
*
* For bracket sports, prefer calling recordMatchScoreEvents instead it computes
* the exact per-season delta from scoring rules rather than requiring the caller
* to supply a pre-computed pointsDelta.
*/
export async function recordTeamScoreEvent(
params: {
teamId: string;
seasonId: string;
scoringEventId: string;
scoringEventName: string | null;
sportName: string | null;
participantIds: string[];
pointsDelta: number;
occurredAt?: Date;
matchId?: string;
},
providedDb?: ReturnType<typeof database>
): Promise<void> {
const db = providedDb || database();
const values = {
teamId: params.teamId,
seasonId: params.seasonId,
scoringEventId: params.scoringEventId,
scoringEventName: params.scoringEventName,
sportName: params.sportName,
matchId: params.matchId ?? null,
participantIds: params.participantIds,
pointsDelta: params.pointsDelta.toString(),
occurredAt: params.occurredAt ?? new Date(),
};
if (params.matchId) {
// Per-match path: unique on (teamId, seasonId, matchId) WHERE matchId IS NOT NULL
await db
.insert(schema.teamScoreEvents)
.values(values)
.onConflictDoUpdate({
target: [
schema.teamScoreEvents.teamId,
schema.teamScoreEvents.seasonId,
schema.teamScoreEvents.matchId,
],
targetWhere: sql`match_id IS NOT NULL`,
set: {
participantIds: params.participantIds,
pointsDelta: params.pointsDelta.toString(),
},
});
} else {
// Event-level fallback: unique on (teamId, seasonId, scoringEventId) WHERE matchId IS NULL
await db
.insert(schema.teamScoreEvents)
.values(values)
.onConflictDoUpdate({
target: [
schema.teamScoreEvents.teamId,
schema.teamScoreEvents.seasonId,
schema.teamScoreEvents.scoringEventId,
],
targetWhere: sql`match_id IS NULL`,
set: {
participantIds: params.participantIds,
pointsDelta: params.pointsDelta.toString(),
},
});
}
}
/**
* Records a score event for every fantasy season that uses the given sports season,
* attributing the exact point delta to the specific match winner.
*
* Called from processMatchResult immediately after upsertParticipantResult sets the
* winner's new floor, so the delta is computed from the exact position change rather
* than from aggregate before/after standings totals.
*
* oldFloor is 0 when the participant had no prior result row (first match win).
*/
export async function recordMatchScoreEvents(
params: {
participantId: string;
sportsSeasonId: string;
oldFloor: number;
newFloor: number;
bracketTemplateId: string | null;
matchId: string;
eventId: string;
eventName: string | null;
},
providedDb?: ReturnType<typeof database>
): Promise<void> {
const db = providedDb || database();
// Fetch sport name for display (one query, shared across all seasons)
const sportsSeason = await db.query.sportsSeasons.findFirst({
where: eq(schema.sportsSeasons.id, params.sportsSeasonId),
with: { sport: { columns: { name: true } } },
});
const sportName = sportsSeason?.sport?.name ?? null;
// All fantasy seasons that include this sports season
const seasonSports = await db.query.seasonSports.findMany({
where: eq(schema.seasonSports.sportsSeasonId, params.sportsSeasonId),
columns: { seasonId: true },
});
if (seasonSports.length === 0) return;
const seasonIds = seasonSports.map((ss) => ss.seasonId);
// Batch fetch: which team in each season drafted this participant?
const picks = await db.query.draftPicks.findMany({
where: and(
inArray(schema.draftPicks.seasonId, seasonIds),
eq(schema.draftPicks.participantId, params.participantId)
),
columns: { teamId: true, seasonId: true },
});
if (picks.length === 0) return;
const teamBySeasonId = new Map(picks.map((p) => [p.seasonId, p.teamId]));
// Batch fetch scoring rules for all seasons in one query
const seasonRows = await db.query.seasons.findMany({
where: inArray(schema.seasons.id, seasonIds),
columns: {
id: true,
pointsFor1st: true, pointsFor2nd: true, pointsFor3rd: true,
pointsFor4th: true, pointsFor5th: true, pointsFor6th: true,
pointsFor7th: true, pointsFor8th: true,
},
});
const rulesBySeasonId = new Map<string, ScoringRules>(
seasonRows.map((s) => [s.id, {
pointsFor1st: s.pointsFor1st, pointsFor2nd: s.pointsFor2nd,
pointsFor3rd: s.pointsFor3rd, pointsFor4th: s.pointsFor4th,
pointsFor5th: s.pointsFor5th, pointsFor6th: s.pointsFor6th,
pointsFor7th: s.pointsFor7th, pointsFor8th: s.pointsFor8th,
}])
);
for (const seasonId of seasonIds) {
const teamId = teamBySeasonId.get(seasonId);
if (!teamId) continue;
const rules = rulesBySeasonId.get(seasonId);
if (!rules) continue;
const delta =
calculateBracketPoints(params.newFloor, rules, params.bracketTemplateId) -
calculateBracketPoints(params.oldFloor, rules, params.bracketTemplateId);
if (delta <= 0) continue;
try {
await recordTeamScoreEvent(
{
teamId,
seasonId,
scoringEventId: params.eventId,
scoringEventName: params.eventName,
sportName,
participantIds: [params.participantId],
pointsDelta: delta,
matchId: params.matchId,
},
db
);
} catch (err) {
logger.error(
`[TeamScoreEvents] Failed to record match score event for team ${teamId} match ${params.matchId}:`,
err
);
}
}
}
export interface TeamScoreEventEntry {
id: string;
teamId: string;
teamName: string;
scoringEventId: string | null;
scoringEventName: string | null;
sportName: string | null;
pointsDelta: string;
occurredAt: Date;
participants: Array<{ id: string; name: string }>;
}
/**
* Returns the most recent scoring events for a league season, ordered by
* occurredAt DESC. Participant names are fetched from the stored participantIds.
*/
export async function getRecentTeamScoreEvents(
seasonId: string,
limit = 10,
providedDb?: ReturnType<typeof database>
): Promise<TeamScoreEventEntry[]> {
const db = providedDb || database();
const rows = await db.query.teamScoreEvents.findMany({
where: eq(schema.teamScoreEvents.seasonId, seasonId),
with: {
team: { columns: { id: true, name: true } },
},
orderBy: [desc(schema.teamScoreEvents.occurredAt)],
limit,
});
if (rows.length === 0) return [];
// Batch-fetch participant names for all stored participant IDs
const allParticipantIds = [
...new Set(rows.flatMap((r) => r.participantIds ?? [])),
];
const participantNameById = new Map<string, string>();
if (allParticipantIds.length > 0) {
const participantRows = await db.query.participants.findMany({
where: inArray(schema.participants.id, allParticipantIds),
columns: { id: true, name: true },
});
for (const p of participantRows) {
participantNameById.set(p.id, p.name);
}
}
return rows.map((row) => ({
id: row.id,
teamId: row.teamId,
teamName: row.team.name,
scoringEventId: row.scoringEventId,
scoringEventName: row.scoringEventName,
sportName: row.sportName,
pointsDelta: row.pointsDelta,
occurredAt: row.occurredAt,
participants: (row.participantIds ?? [])
.map((id) => {
const name = participantNameById.get(id);
return name ? { id, name } : null;
})
.filter((p): p is { id: string; name: string } => p !== null),
}));
}