Add audit logging for commissioner actions (#293)
Closes #144
* feat: add commissioner audit log for league transparency (issue #144)
Adds a complete audit log system so league members can verify that
settings, draft order, picks, and time banks have not been quietly
changed without their awareness.
Changes:
- database/schema.ts: new `audit_action` enum + `commissioner_audit_log`
table (seasonId, leagueId, actorClerkId, actorDisplayName, action,
affectedTeamIds[], details jsonb, createdAt)
- drizzle/0075: generated migration for the new table
- app/models/audit-log.ts: createAuditLogEntry, getAuditLogForSeason
(paginated), logCommissionerAction (resolves display name automatically)
- app/lib/audit-log-display.ts: shared formatAuditDetail() helper used by
both the league home widget and the full audit log page
- app/routes/leagues/$leagueId.audit-log.tsx: new read-only route at
/leagues/:id/audit-log, accessible to all league members, with
action-type filter and pagination
- app/routes.ts: registers the new route
- League home page ($leagueId.server.ts / $leagueId.tsx): "Recent Activity"
summary card showing the last 5 entries with "View all" link
- Settings page ($leagueId.settings.tsx): "View Full Audit Log" link card;
audit log calls added for league/draft settings changes, draft order
set/randomized, and draft reset
- API routes: audit log calls added to draft.start, draft.pause,
draft.resume, draft.rollback, draft.adjust-time-bank, draft.force-autopick,
draft.force-manual-pick, draft.replace-pick
- Tests: 11 new unit tests for the audit-log model; mocks added to 3
existing route test files to account for the new logCommissionerAction call
https://claude.ai/code/session_01NdiwK2fbtKhAD3XuD58fTm
* fix: validate action filter URL param against known enum values
The action filter on the audit log route was cast directly from the URL
search param to AuditAction without validation. An invalid value would
be passed into the Drizzle inArray() call, potentially throwing a
PostgreSQL enum type error. Now validates against the actual enum values
before using the filter.
https://claude.ai/code/session_01NdiwK2fbtKhAD3XuD58fTm
* Fix lint errors: use !== instead of != and toSorted instead of sort
https://claude.ai/code/session_01NdiwK2fbtKhAD3XuD58fTm
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-04-13 18:45:39 -04:00
|
|
|
|
import { integer, pgTable, varchar, uuid, timestamp, pgEnum, boolean, text, date, decimal, uniqueIndex, index, jsonb } from "drizzle-orm/pg-core";
|
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 { relations, sql } from "drizzle-orm";
|
2025-10-10 23:04:50 -07:00
|
|
|
|
|
2025-10-11 00:53:39 -07:00
|
|
|
|
export const users = pgTable("users", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
2026-04-29 10:03:50 -07:00
|
|
|
|
clerkId: varchar("clerk_id", { length: 255 }).unique(), // legacy: only populated for users migrated from Clerk; new users are null
|
2025-10-11 00:53:39 -07:00
|
|
|
|
email: varchar("email", { length: 255 }).notNull(),
|
Migrate authentication from Clerk to BetterAuth (#324)
* Migrate authentication from Clerk to BetterAuth (#322)
Replaces @clerk/react-router with self-hosted better-auth to eliminate
the external Clerk dependency and keep all user/session data in our own
PostgreSQL database.
**What changed**
- New: auth.server.ts (BetterAuth config w/ Drizzle adapter, bcrypt, Resend), auth-client.ts, api.auth.$.ts handler
- New: /login and /register pages with email+password and Google/Discord OAuth; open-redirect guard on redirectTo param
- New: UserMenu component replacing Clerk's UserButton
- Schema: sessions, accounts, verifications tables; emailVerified column; clerkId made nullable
- Migrations 0081 (BetterAuth tables) and 0082 (accounts extra columns for v1.6.9)
- All ~30 route files: getAuth → auth.api.getSession, isUserAdminByClerkId → isUserAdmin
- root.tsx: isAdmin read directly from session.user.isAdmin (no extra DB query)
- useDraftAuthRecovery: removed Clerk JWT refresh logic; replaced with cookie-session check
- models/user.ts: removed findUserByClerkId, findOrCreateUser, updateUserByClerkId (webhook pattern)
- Deleted: app/routes/api/webhooks/clerk.ts; uninstalled @clerk/react-router, @clerk/themes, svix
- scripts/migrate.mjs: extended with idempotent Clerk → BetterAuth data migration (FK conversion, email_verified, OAuth accounts)
- scripts/migrate-clerk-passwords.mjs: one-time script to import bcrypt hashes from Clerk CSV export
- BETTERAUTH_MIGRATION.md: dev and production runbooks
- All test mocks updated: vi.mock('~/lib/auth.server') instead of @clerk/react-router/server
- Test fixtures: added emailVerified field
**Follow-up (post-stable)**
- Rename actor_clerk_id column → actor_user_id in commissioner_audit_log
- Drop clerk_id column from users once migration confirmed
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Add .npmrc with legacy-peer-deps for better-auth/drizzle peer dep conflict
better-auth@1.6.9 declares peerOptional deps on drizzle-orm ^0.45.2 and
drizzle-kit >=0.31.4, but we run drizzle-orm ~0.36.3 / drizzle-kit ~0.28.1.
The adapter works correctly at runtime with our versions — the peer dep is
only for stricter type checking. This unblocks npm ci in CI without a risky
drizzle major-version upgrade.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 22:00:49 -07:00
|
|
|
|
emailVerified: boolean("email_verified").notNull().default(false),
|
2025-10-14 21:20:58 -07:00
|
|
|
|
username: varchar("username", { length: 255 }),
|
Migrate authentication from Clerk to BetterAuth (#324)
* Migrate authentication from Clerk to BetterAuth (#322)
Replaces @clerk/react-router with self-hosted better-auth to eliminate
the external Clerk dependency and keep all user/session data in our own
PostgreSQL database.
**What changed**
- New: auth.server.ts (BetterAuth config w/ Drizzle adapter, bcrypt, Resend), auth-client.ts, api.auth.$.ts handler
- New: /login and /register pages with email+password and Google/Discord OAuth; open-redirect guard on redirectTo param
- New: UserMenu component replacing Clerk's UserButton
- Schema: sessions, accounts, verifications tables; emailVerified column; clerkId made nullable
- Migrations 0081 (BetterAuth tables) and 0082 (accounts extra columns for v1.6.9)
- All ~30 route files: getAuth → auth.api.getSession, isUserAdminByClerkId → isUserAdmin
- root.tsx: isAdmin read directly from session.user.isAdmin (no extra DB query)
- useDraftAuthRecovery: removed Clerk JWT refresh logic; replaced with cookie-session check
- models/user.ts: removed findUserByClerkId, findOrCreateUser, updateUserByClerkId (webhook pattern)
- Deleted: app/routes/api/webhooks/clerk.ts; uninstalled @clerk/react-router, @clerk/themes, svix
- scripts/migrate.mjs: extended with idempotent Clerk → BetterAuth data migration (FK conversion, email_verified, OAuth accounts)
- scripts/migrate-clerk-passwords.mjs: one-time script to import bcrypt hashes from Clerk CSV export
- BETTERAUTH_MIGRATION.md: dev and production runbooks
- All test mocks updated: vi.mock('~/lib/auth.server') instead of @clerk/react-router/server
- Test fixtures: added emailVerified field
**Follow-up (post-stable)**
- Rename actor_clerk_id column → actor_user_id in commissioner_audit_log
- Drop clerk_id column from users once migration confirmed
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Add .npmrc with legacy-peer-deps for better-auth/drizzle peer dep conflict
better-auth@1.6.9 declares peerOptional deps on drizzle-orm ^0.45.2 and
drizzle-kit >=0.31.4, but we run drizzle-orm ~0.36.3 / drizzle-kit ~0.28.1.
The adapter works correctly at runtime with our versions — the peer dep is
only for stricter type checking. This unblocks npm ci in CI without a risky
drizzle major-version upgrade.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 22:00:49 -07:00
|
|
|
|
displayName: varchar("display_name", { length: 255 }), // mapped as BetterAuth's "name" field
|
2025-10-11 00:53:39 -07:00
|
|
|
|
firstName: varchar("first_name", { length: 255 }),
|
|
|
|
|
|
lastName: varchar("last_name", { length: 255 }),
|
Migrate authentication from Clerk to BetterAuth (#324)
* Migrate authentication from Clerk to BetterAuth (#322)
Replaces @clerk/react-router with self-hosted better-auth to eliminate
the external Clerk dependency and keep all user/session data in our own
PostgreSQL database.
**What changed**
- New: auth.server.ts (BetterAuth config w/ Drizzle adapter, bcrypt, Resend), auth-client.ts, api.auth.$.ts handler
- New: /login and /register pages with email+password and Google/Discord OAuth; open-redirect guard on redirectTo param
- New: UserMenu component replacing Clerk's UserButton
- Schema: sessions, accounts, verifications tables; emailVerified column; clerkId made nullable
- Migrations 0081 (BetterAuth tables) and 0082 (accounts extra columns for v1.6.9)
- All ~30 route files: getAuth → auth.api.getSession, isUserAdminByClerkId → isUserAdmin
- root.tsx: isAdmin read directly from session.user.isAdmin (no extra DB query)
- useDraftAuthRecovery: removed Clerk JWT refresh logic; replaced with cookie-session check
- models/user.ts: removed findUserByClerkId, findOrCreateUser, updateUserByClerkId (webhook pattern)
- Deleted: app/routes/api/webhooks/clerk.ts; uninstalled @clerk/react-router, @clerk/themes, svix
- scripts/migrate.mjs: extended with idempotent Clerk → BetterAuth data migration (FK conversion, email_verified, OAuth accounts)
- scripts/migrate-clerk-passwords.mjs: one-time script to import bcrypt hashes from Clerk CSV export
- BETTERAUTH_MIGRATION.md: dev and production runbooks
- All test mocks updated: vi.mock('~/lib/auth.server') instead of @clerk/react-router/server
- Test fixtures: added emailVerified field
**Follow-up (post-stable)**
- Rename actor_clerk_id column → actor_user_id in commissioner_audit_log
- Drop clerk_id column from users once migration confirmed
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Add .npmrc with legacy-peer-deps for better-auth/drizzle peer dep conflict
better-auth@1.6.9 declares peerOptional deps on drizzle-orm ^0.45.2 and
drizzle-kit >=0.31.4, but we run drizzle-orm ~0.36.3 / drizzle-kit ~0.28.1.
The adapter works correctly at runtime with our versions — the peer dep is
only for stricter type checking. This unblocks npm ci in CI without a risky
drizzle major-version upgrade.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 22:00:49 -07:00
|
|
|
|
imageUrl: varchar("image_url", { length: 512 }), // mapped as BetterAuth's "image" field
|
2025-10-12 21:16:00 -07:00
|
|
|
|
isAdmin: boolean("is_admin").notNull().default(false),
|
2026-04-26 22:31:52 -07:00
|
|
|
|
timezone: varchar("timezone", { length: 50 }), // IANA timezone string, e.g. "America/Chicago"
|
2025-10-11 00:53:39 -07:00
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
Migrate authentication from Clerk to BetterAuth (#324)
* Migrate authentication from Clerk to BetterAuth (#322)
Replaces @clerk/react-router with self-hosted better-auth to eliminate
the external Clerk dependency and keep all user/session data in our own
PostgreSQL database.
**What changed**
- New: auth.server.ts (BetterAuth config w/ Drizzle adapter, bcrypt, Resend), auth-client.ts, api.auth.$.ts handler
- New: /login and /register pages with email+password and Google/Discord OAuth; open-redirect guard on redirectTo param
- New: UserMenu component replacing Clerk's UserButton
- Schema: sessions, accounts, verifications tables; emailVerified column; clerkId made nullable
- Migrations 0081 (BetterAuth tables) and 0082 (accounts extra columns for v1.6.9)
- All ~30 route files: getAuth → auth.api.getSession, isUserAdminByClerkId → isUserAdmin
- root.tsx: isAdmin read directly from session.user.isAdmin (no extra DB query)
- useDraftAuthRecovery: removed Clerk JWT refresh logic; replaced with cookie-session check
- models/user.ts: removed findUserByClerkId, findOrCreateUser, updateUserByClerkId (webhook pattern)
- Deleted: app/routes/api/webhooks/clerk.ts; uninstalled @clerk/react-router, @clerk/themes, svix
- scripts/migrate.mjs: extended with idempotent Clerk → BetterAuth data migration (FK conversion, email_verified, OAuth accounts)
- scripts/migrate-clerk-passwords.mjs: one-time script to import bcrypt hashes from Clerk CSV export
- BETTERAUTH_MIGRATION.md: dev and production runbooks
- All test mocks updated: vi.mock('~/lib/auth.server') instead of @clerk/react-router/server
- Test fixtures: added emailVerified field
**Follow-up (post-stable)**
- Rename actor_clerk_id column → actor_user_id in commissioner_audit_log
- Drop clerk_id column from users once migration confirmed
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Add .npmrc with legacy-peer-deps for better-auth/drizzle peer dep conflict
better-auth@1.6.9 declares peerOptional deps on drizzle-orm ^0.45.2 and
drizzle-kit >=0.31.4, but we run drizzle-orm ~0.36.3 / drizzle-kit ~0.28.1.
The adapter works correctly at runtime with our versions — the peer dep is
only for stricter type checking. This unblocks npm ci in CI without a risky
drizzle major-version upgrade.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 22:00:49 -07:00
|
|
|
|
// BetterAuth session/account/verification tables
|
|
|
|
|
|
export const sessions = pgTable("sessions", {
|
2026-04-29 10:03:50 -07:00
|
|
|
|
id: text("id").primaryKey().$defaultFn(() => crypto.randomUUID()),
|
Migrate authentication from Clerk to BetterAuth (#324)
* Migrate authentication from Clerk to BetterAuth (#322)
Replaces @clerk/react-router with self-hosted better-auth to eliminate
the external Clerk dependency and keep all user/session data in our own
PostgreSQL database.
**What changed**
- New: auth.server.ts (BetterAuth config w/ Drizzle adapter, bcrypt, Resend), auth-client.ts, api.auth.$.ts handler
- New: /login and /register pages with email+password and Google/Discord OAuth; open-redirect guard on redirectTo param
- New: UserMenu component replacing Clerk's UserButton
- Schema: sessions, accounts, verifications tables; emailVerified column; clerkId made nullable
- Migrations 0081 (BetterAuth tables) and 0082 (accounts extra columns for v1.6.9)
- All ~30 route files: getAuth → auth.api.getSession, isUserAdminByClerkId → isUserAdmin
- root.tsx: isAdmin read directly from session.user.isAdmin (no extra DB query)
- useDraftAuthRecovery: removed Clerk JWT refresh logic; replaced with cookie-session check
- models/user.ts: removed findUserByClerkId, findOrCreateUser, updateUserByClerkId (webhook pattern)
- Deleted: app/routes/api/webhooks/clerk.ts; uninstalled @clerk/react-router, @clerk/themes, svix
- scripts/migrate.mjs: extended with idempotent Clerk → BetterAuth data migration (FK conversion, email_verified, OAuth accounts)
- scripts/migrate-clerk-passwords.mjs: one-time script to import bcrypt hashes from Clerk CSV export
- BETTERAUTH_MIGRATION.md: dev and production runbooks
- All test mocks updated: vi.mock('~/lib/auth.server') instead of @clerk/react-router/server
- Test fixtures: added emailVerified field
**Follow-up (post-stable)**
- Rename actor_clerk_id column → actor_user_id in commissioner_audit_log
- Drop clerk_id column from users once migration confirmed
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Add .npmrc with legacy-peer-deps for better-auth/drizzle peer dep conflict
better-auth@1.6.9 declares peerOptional deps on drizzle-orm ^0.45.2 and
drizzle-kit >=0.31.4, but we run drizzle-orm ~0.36.3 / drizzle-kit ~0.28.1.
The adapter works correctly at runtime with our versions — the peer dep is
only for stricter type checking. This unblocks npm ci in CI without a risky
drizzle major-version upgrade.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 22:00:49 -07:00
|
|
|
|
expiresAt: timestamp("expires_at").notNull(),
|
|
|
|
|
|
token: text("token").notNull().unique(),
|
|
|
|
|
|
userId: uuid("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
|
|
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
ipAddress: text("ip_address"),
|
|
|
|
|
|
userAgent: text("user_agent"),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
export const accounts = pgTable("accounts", {
|
2026-04-29 10:03:50 -07:00
|
|
|
|
id: text("id").primaryKey().$defaultFn(() => crypto.randomUUID()),
|
Migrate authentication from Clerk to BetterAuth (#324)
* Migrate authentication from Clerk to BetterAuth (#322)
Replaces @clerk/react-router with self-hosted better-auth to eliminate
the external Clerk dependency and keep all user/session data in our own
PostgreSQL database.
**What changed**
- New: auth.server.ts (BetterAuth config w/ Drizzle adapter, bcrypt, Resend), auth-client.ts, api.auth.$.ts handler
- New: /login and /register pages with email+password and Google/Discord OAuth; open-redirect guard on redirectTo param
- New: UserMenu component replacing Clerk's UserButton
- Schema: sessions, accounts, verifications tables; emailVerified column; clerkId made nullable
- Migrations 0081 (BetterAuth tables) and 0082 (accounts extra columns for v1.6.9)
- All ~30 route files: getAuth → auth.api.getSession, isUserAdminByClerkId → isUserAdmin
- root.tsx: isAdmin read directly from session.user.isAdmin (no extra DB query)
- useDraftAuthRecovery: removed Clerk JWT refresh logic; replaced with cookie-session check
- models/user.ts: removed findUserByClerkId, findOrCreateUser, updateUserByClerkId (webhook pattern)
- Deleted: app/routes/api/webhooks/clerk.ts; uninstalled @clerk/react-router, @clerk/themes, svix
- scripts/migrate.mjs: extended with idempotent Clerk → BetterAuth data migration (FK conversion, email_verified, OAuth accounts)
- scripts/migrate-clerk-passwords.mjs: one-time script to import bcrypt hashes from Clerk CSV export
- BETTERAUTH_MIGRATION.md: dev and production runbooks
- All test mocks updated: vi.mock('~/lib/auth.server') instead of @clerk/react-router/server
- Test fixtures: added emailVerified field
**Follow-up (post-stable)**
- Rename actor_clerk_id column → actor_user_id in commissioner_audit_log
- Drop clerk_id column from users once migration confirmed
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Add .npmrc with legacy-peer-deps for better-auth/drizzle peer dep conflict
better-auth@1.6.9 declares peerOptional deps on drizzle-orm ^0.45.2 and
drizzle-kit >=0.31.4, but we run drizzle-orm ~0.36.3 / drizzle-kit ~0.28.1.
The adapter works correctly at runtime with our versions — the peer dep is
only for stricter type checking. This unblocks npm ci in CI without a risky
drizzle major-version upgrade.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 22:00:49 -07:00
|
|
|
|
accountId: text("account_id").notNull(),
|
|
|
|
|
|
providerId: text("provider_id").notNull(),
|
|
|
|
|
|
userId: uuid("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
|
|
|
|
|
|
accessToken: text("access_token"),
|
|
|
|
|
|
refreshToken: text("refresh_token"),
|
|
|
|
|
|
idToken: text("id_token"),
|
|
|
|
|
|
expiresAt: timestamp("expires_at"),
|
|
|
|
|
|
accessTokenExpiresAt: timestamp("access_token_expires_at"),
|
|
|
|
|
|
refreshTokenExpiresAt: timestamp("refresh_token_expires_at"),
|
|
|
|
|
|
scope: text("scope"),
|
|
|
|
|
|
password: text("password"),
|
|
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
export const verifications = pgTable("verifications", {
|
2026-04-29 10:03:50 -07:00
|
|
|
|
id: text("id").primaryKey().$defaultFn(() => crypto.randomUUID()),
|
Migrate authentication from Clerk to BetterAuth (#324)
* Migrate authentication from Clerk to BetterAuth (#322)
Replaces @clerk/react-router with self-hosted better-auth to eliminate
the external Clerk dependency and keep all user/session data in our own
PostgreSQL database.
**What changed**
- New: auth.server.ts (BetterAuth config w/ Drizzle adapter, bcrypt, Resend), auth-client.ts, api.auth.$.ts handler
- New: /login and /register pages with email+password and Google/Discord OAuth; open-redirect guard on redirectTo param
- New: UserMenu component replacing Clerk's UserButton
- Schema: sessions, accounts, verifications tables; emailVerified column; clerkId made nullable
- Migrations 0081 (BetterAuth tables) and 0082 (accounts extra columns for v1.6.9)
- All ~30 route files: getAuth → auth.api.getSession, isUserAdminByClerkId → isUserAdmin
- root.tsx: isAdmin read directly from session.user.isAdmin (no extra DB query)
- useDraftAuthRecovery: removed Clerk JWT refresh logic; replaced with cookie-session check
- models/user.ts: removed findUserByClerkId, findOrCreateUser, updateUserByClerkId (webhook pattern)
- Deleted: app/routes/api/webhooks/clerk.ts; uninstalled @clerk/react-router, @clerk/themes, svix
- scripts/migrate.mjs: extended with idempotent Clerk → BetterAuth data migration (FK conversion, email_verified, OAuth accounts)
- scripts/migrate-clerk-passwords.mjs: one-time script to import bcrypt hashes from Clerk CSV export
- BETTERAUTH_MIGRATION.md: dev and production runbooks
- All test mocks updated: vi.mock('~/lib/auth.server') instead of @clerk/react-router/server
- Test fixtures: added emailVerified field
**Follow-up (post-stable)**
- Rename actor_clerk_id column → actor_user_id in commissioner_audit_log
- Drop clerk_id column from users once migration confirmed
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Add .npmrc with legacy-peer-deps for better-auth/drizzle peer dep conflict
better-auth@1.6.9 declares peerOptional deps on drizzle-orm ^0.45.2 and
drizzle-kit >=0.31.4, but we run drizzle-orm ~0.36.3 / drizzle-kit ~0.28.1.
The adapter works correctly at runtime with our versions — the peer dep is
only for stricter type checking. This unblocks npm ci in CI without a risky
drizzle major-version upgrade.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 22:00:49 -07:00
|
|
|
|
identifier: text("identifier").notNull(),
|
|
|
|
|
|
value: text("value").notNull(),
|
|
|
|
|
|
expiresAt: timestamp("expires_at").notNull(),
|
|
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
2025-10-11 00:07:39 -07:00
|
|
|
|
// Fantasy League Tables
|
|
|
|
|
|
export const seasonStatusEnum = pgEnum("season_status", [
|
|
|
|
|
|
"pre_draft",
|
|
|
|
|
|
"draft",
|
|
|
|
|
|
"active",
|
|
|
|
|
|
"completed",
|
|
|
|
|
|
]);
|
|
|
|
|
|
|
2025-10-12 21:16:00 -07:00
|
|
|
|
// Sports Tables - Enums
|
|
|
|
|
|
export const sportTypeEnum = pgEnum("sport_type", ["team", "individual"]);
|
|
|
|
|
|
|
|
|
|
|
|
export const sportsSeasonStatusEnum = pgEnum("sports_season_status", [
|
|
|
|
|
|
"upcoming",
|
|
|
|
|
|
"active",
|
|
|
|
|
|
"completed",
|
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
|
|
export const scoringTypeEnum = pgEnum("scoring_type", [
|
|
|
|
|
|
"playoffs",
|
|
|
|
|
|
"regular_season",
|
|
|
|
|
|
"majors",
|
|
|
|
|
|
]);
|
|
|
|
|
|
|
2025-10-28 23:39:34 -07:00
|
|
|
|
export const scoringPatternEnum = pgEnum("scoring_pattern", [
|
2026-03-07 21:59:29 -08:00
|
|
|
|
"playoff_bracket",
|
2025-10-28 23:39:34 -07:00
|
|
|
|
"season_standings",
|
|
|
|
|
|
"qualifying_points",
|
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
|
|
export const eventTypeEnum = pgEnum("event_type", [
|
|
|
|
|
|
"playoff_game",
|
|
|
|
|
|
"major_tournament",
|
|
|
|
|
|
"final_standings",
|
2026-03-07 21:59:29 -08:00
|
|
|
|
"schedule_event",
|
2025-10-28 23:39:34 -07:00
|
|
|
|
]);
|
|
|
|
|
|
|
2025-10-16 00:32:48 -07:00
|
|
|
|
export const pickedByTypeEnum = pgEnum("picked_by_type", [
|
|
|
|
|
|
"owner",
|
|
|
|
|
|
"commissioner",
|
Grant sitewide admins commissioner-level access in leagues (#162)
* Grant sitewide admins commissioner-level access in leagues
- `isCommissioner()` now returns true for site admins, covering all
commissioner-gated loaders (league home, settings, sport season detail)
and draft API routes (start, pause, resume, rollback, replace-pick,
force-autopick, force-manual-pick, adjust-time-bank, make-pick)
- Added `hasCommissionerRecord()` (DB-only, no admin bypass) for the
"already a commissioner" duplicate-entry check in the settings action,
preventing a false positive when adding a site admin as commissioner
- `isCommissioner()` now runs the admin check and DB query in parallel
via Promise.all to avoid a serial roundtrip on every check
- Added "admin" to the `picked_by_type` enum (migration 0049) so picks
forced by a site admin are recorded accurately in the audit log rather
than as "commissioner"
- 8 unit tests covering both isCommissioner and hasCommissionerRecord
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix draft.force-manual-pick tests broken by isUserAdminByClerkId
The route now calls isUserAdminByClerkId which hits database().query.users,
but the test's mock DB had no query.users entry. Add a vi.mock for
~/models/user and default isUserAdminByClerkId to false in beforeEach.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-18 00:41:56 -07:00
|
|
|
|
"admin",
|
2025-10-16 00:32:48 -07:00
|
|
|
|
"auto",
|
|
|
|
|
|
]);
|
|
|
|
|
|
|
2025-10-21 23:22:17 -07:00
|
|
|
|
export const autodraftModeEnum = pgEnum("autodraft_mode", [
|
|
|
|
|
|
"next_pick",
|
|
|
|
|
|
"while_on",
|
|
|
|
|
|
]);
|
|
|
|
|
|
|
2026-03-20 21:36:39 -07:00
|
|
|
|
export const draftTimerModeEnum = pgEnum("draft_timer_mode", [
|
|
|
|
|
|
"chess_clock",
|
|
|
|
|
|
"standard",
|
|
|
|
|
|
]);
|
|
|
|
|
|
|
2026-04-26 22:31:52 -07:00
|
|
|
|
export const overnightPauseModeEnum = pgEnum("overnight_pause_mode", [
|
|
|
|
|
|
"none",
|
|
|
|
|
|
"league",
|
|
|
|
|
|
"per_user",
|
|
|
|
|
|
]);
|
|
|
|
|
|
|
2025-11-17 22:19:46 -08:00
|
|
|
|
export const probabilitySourceEnum = pgEnum("probability_source", [
|
|
|
|
|
|
"manual",
|
|
|
|
|
|
"futures_odds",
|
|
|
|
|
|
"elo_simulation",
|
|
|
|
|
|
"performance_model",
|
|
|
|
|
|
]);
|
|
|
|
|
|
|
2026-03-09 15:34:31 -07:00
|
|
|
|
export const simulationStatusEnum = pgEnum("simulation_status", [
|
|
|
|
|
|
"idle",
|
|
|
|
|
|
"running",
|
|
|
|
|
|
"failed",
|
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
|
|
export const simulatorTypeEnum = pgEnum("simulator_type", [
|
|
|
|
|
|
"f1_standings",
|
|
|
|
|
|
"indycar_standings",
|
|
|
|
|
|
"golf_qualifying_points",
|
|
|
|
|
|
"playoff_bracket",
|
2026-03-10 23:04:51 -07:00
|
|
|
|
"ucl_bracket",
|
Add NCAAM and NCAAW bracket Monte Carlo simulators (#150)
- NCAAM: KenPom AEM logistic formula (1/(1+exp(-diff/7.5))), data through 2025-26 March 15
- NCAAW: Barttorvik Barthag Log5 formula (A*(1-B)/(A*(1-B)+B*(1-A))), same bracket structure
- Both simulators: 50,000-iteration Monte Carlo, First Four simulation, honors completed matches
- Track E8+ placements only: champion, finalist, FF losers (3rd/4th), E8 losers (5th–8th)
- Add bracket configuration validation: null R64 slots must exactly match First Four mapping
- Fix DEFAULT_SCORING_RULES to 100/70/45/45/20/20/20/20 (3rd/4th=45, 5th–8th=20)
- Align scoring constants across simulate route, expected-values display, and server action
- Zero out EVs for non-bracket participants on every simulation run (prevents EV inflation)
- Add EV total invariant warning (expected ~340) on expected-values admin page
- 98 unit tests across NCAAM, NCAAW, and UCL simulators — all passing
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-15 23:31:47 -07:00
|
|
|
|
"ncaam_bracket",
|
|
|
|
|
|
"ncaaw_bracket",
|
2026-03-16 21:43:39 -07:00
|
|
|
|
"nba_bracket",
|
2026-03-18 01:23:53 -07:00
|
|
|
|
"nhl_bracket",
|
2026-04-07 09:39:34 -04:00
|
|
|
|
"nfl_bracket",
|
2026-03-22 01:57:39 -07:00
|
|
|
|
"afl_bracket",
|
2026-03-23 08:24:28 -07:00
|
|
|
|
"snooker_bracket",
|
Add tennis Grand Slam simulator with surface Elo ratings, fixes #116 (#216)
Implements a Monte Carlo simulator for men's/women's tennis seasons scored
on the qualifying_points pattern. Simulates all 4 Grand Slam majors
(Australian Open, French Open, Wimbledon, US Open) using surface-specific
Elo ratings and ATP/WTA world rankings for seeding.
New table: participant_surface_elos — one row per (participant, season)
storing worldRanking, eloHard, eloClay, eloGrass.
Key design decisions:
- Seeding uses ATP/WTA world ranking (not Elo), matching real draw procedure
- Top 32 seeded with standard slot placement (1→0, 2→64, 3-4→quarters, etc.)
- QP per round with tie-splitting pre-applied: W=20, F=14, SF=9, QF=4, R16=1.5
- Completed majors read actual qualifyingPointsAwarded from eventResults
- 10,000 Monte Carlo simulations; column sums naturally 1.0 (no normalization)
Admin UI at /admin/sports-seasons/:id/surface-elo:
- 5-column grid (Player | Rank | Hard | Clay | Grass)
- Bulk import: "Name, ranking, hardElo, clayElo, grassElo" one per line
- Fuzzy name matching (bigram Dice coefficient) with "Did you mean?" suggestions
- Inline participant creation for unmatched names via useFetcher
- Saves Elos and auto-runs simulation on submit
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-23 23:59:35 -07:00
|
|
|
|
"tennis_qualifying_points",
|
Add MLB playoff simulator with AL/NL division standings, fixes #121 (#225)
* Add MLB playoff simulator with AL/NL division standings, fixes #121
- New `mlb-simulator.ts`: 50k Monte Carlo sim drawing division winners
(weighted by p_div) and 3 WC teams per league, then simulating
WC best-of-3 → DS best-of-5 → LCS best-of-7 → World Series.
Elo parity factor 350; blends Vegas odds 30/70 when sourceOdds available.
- New `standings-sync/mlb.ts`: adapter for free statsapi.mlb.com API,
mapping AL/NL conferences, division ranks, streaks, home/away/L10 splits.
- New `mlb-divisions` display mode in RegularSeasonStandings: shows 1 division
winner per division section + Wild Card section with 3-spot playoff line,
headings read "AL/NL League" instead of "Conference".
- Refactored buildNhlSections/buildMlbSections into shared buildDivisionSections
(divisionSpots + wcSpots params); conferenceLabel now flows through group
objects rather than being derived from displayMode in the render.
- DB migration 0062 adds `mlb_bracket` to simulator_type enum.
- 37 new tests across simulator, adapter, and component.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix flaky tennis simulator test: increase trials and lower threshold
500 trials with a ~3–5% expected win rate had enough variance to
occasionally land below the 0.03 threshold (~2% failure rate).
Bumping to 2000 trials reduces the std dev by 2x; lowering the
threshold to 0.02 keeps the assertion meaningful (still well above
random 0.78%) while eliminating the flakiness.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-25 08:47:02 -07:00
|
|
|
|
"mlb_bracket",
|
2026-03-26 00:34:51 -07:00
|
|
|
|
"wnba_bracket",
|
Add FIFA World Cup 2026 support with group stage display and Monte Carlo simulator (#242)
* Add FIFA World Cup 2026 support with group stage display and Monte Carlo simulator, fixes #127
- New `groupStageMatches` table for recording group play results (W/D/L, scores, matchday, schedule)
- `computeGroupStandings()` model function: pts → GD → GF → name tiebreaker ordering
- `GroupStageStandings` component showing all 12 groups with standings table and manager column
- Admin bracket UI: group match score entry, per-group standings, "Recalculate Floors" action
- `WorldCupSimulator`: 50k Monte Carlo covering group stage + best-8 3rd-place + knockout + 3rd place game
- Fuzzy name matching for national team Elo lookup (exact → substring → word-overlap), warns on miss
- Partial group completion: completed matches replayed with real scores, remaining matches simulated
- Elo priority: admin-entered sourceElo > futures odds converted to Elo > hardcoded national team ratings
- `fifa_48` bracket template: added Third Place Game round with `loserFeedsInto` on Semifinals
- Scoring rules: distinct 3rd/4th place for `fifa_48` (not averaged), QF losers share 5th–8th equally
- Floor scoring: SF participants guaranteed 4th (provisional), finalized after 3rd place game
- `recalculate-floors` admin action deletes and replays all results from scratch (fixes stale guard bug)
- Unique index on `(tournamentGroupId, participant1Id, participant2Id)` to prevent duplicate pairings
- Batch `findMatchesByGroupIds()` replacing N sequential queries in the sport season loader
- League home mini-standings now shows `actualPoints` (includes floor) instead of `totalPoints` only
- Elo ratings admin page supports World Cup (same bulk-import flow as snooker)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix TypeScript errors: update GroupStandingData type to use findMatchesByGroupIds
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Increase Node heap to 4GB for unit tests in CI to prevent OOM
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix OOM in CI: make WorldCupSimulator simulation count configurable for tests
Tests now pass numSimulations=500 instead of the production default of 50,000.
Six simulator tests × 50k iterations each was exhausting the 4GB heap on GitHub
Actions runners. Also reduce simGroupMatch stat tests from 50k to 5k iterations.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-29 10:27:47 -07:00
|
|
|
|
"world_cup",
|
Add PDC World Darts Championship simulator with Elo-based bracket (#248)
Fixes #123
* Add PDC World Darts Championship simulator (128-player bracket)
- New DartsSimulator: 128-player single-elimination, 7 rounds with
PDC-accurate best-of-sets formats (bo3/bo5/bo5/bo7/bo7/bo11/bo13).
ELO_DIVISOR=500 via set-level Bernoulli model. Two simulation paths:
Path A (bracket drawn) simulates from actual DB matches; Path B
(pre-bracket) seeds top 32 by world ranking in fixed positions and
randomly draws the remaining 96 per simulation run (50,000 iterations).
- darts_bracket added to simulatorTypeEnum and simulator registry.
- world_ranking nullable integer column added to participant_expected_values
(migration 0067); batchSaveSourceElos now accepts and persists it.
- Admin route /admin/sports-seasons/:id/darts-elo: bulk import with format
"Player Name, 2099, 1" (name, Elo, optional world ranking), fuzzy name
matching, auto-runs simulation and updates EV/snapshots on save.
- DARTS_128 bracket template added (scoring starts at Quarterfinals).
- 30 unit tests: math helpers, bracket seeding structure, Path A/B integration.
https://claude.ai/code/session_01WZ6FjMmC2eBeZ1564M9Ruz
* Review fixes: pre-compute hot-loop invariants, import normalizeName
- Pre-compute seededSlots and getSeededMatchOrder(32) before the 50k
simulation loop — was being recomputed every iteration
- Pad unseeded pool to 96 once before the loop instead of inside it
- Inline bracket-building in the hot loop using pre-computed seededSlots;
removes the per-iteration call to buildR1Bracket/getSeededMatchOrder
- Remove dead SEEDED_R1_PAIRS constant (was never referenced)
- Import normalizeName from ~/lib/fuzzy-match instead of redefining it locally
https://claude.ai/code/session_01WZ6FjMmC2eBeZ1564M9Ruz
* Fix lint failures: unused vars, eqeqeq, toSorted
- Remove unused seededSet/unseededSet variables in test
- Replace != null with !== null && !== undefined (eqeqeq rule)
- Replace .sort() with .toSorted() in simulator and route (unicorn/no-array-sort)
https://claude.ai/code/session_01WZ6FjMmC2eBeZ1564M9Ruz
* Fix TS2552: restore seededSet declaration removed during lint fix
https://claude.ai/code/session_01WZ6FjMmC2eBeZ1564M9Ruz
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-31 15:37:28 -07:00
|
|
|
|
"darts_bracket",
|
Add CS2 Major Qualifying Points simulator and stage management (#260)
* Add CS2 Major qualifying points simulator
Implements a full CS2 Major tournament simulator with:
- 3-stage Swiss format (Opening Bo1, Elimination Bo1/Bo3, Decider all Bo3)
+ Champions Stage 8-team single-elimination (QF Bo3, SF Bo3, GF Bo5)
- Monte Carlo simulation (10,000 iterations) accumulating QP across 2 majors/season
- Sampled 24-team field per iteration: top 12 guaranteed, remaining weighted by 1/rank
- Stage 3 exits (placements 9-16) sub-ranked by W-L record (2-3 > 1-3 > 0-3)
- Stage assignments stored per-event so actual field composition drives simulation
- Admin CS Elo form for entering team Elo + HLTV world rankings
- Admin CS2 stage setup page for assigning teams to stages and tracking advancement
- Database migration: cs2_major_qualifying_points enum value + cs2_major_stage_results table
- 24 unit tests covering all exported pure functions
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Consolidate Elo + ranking input into generic elo-ratings page
The darts-elo and cs-elo pages were unreachable from the admin nav,
which always links to the generic elo-ratings page. Extended elo-ratings
to conditionally show world ranking fields for simulator types that need
it (darts_bracket, cs2_major_qualifying_points), then deleted the
redundant sport-specific pages.
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Consolidate server postgres connections into one shared pool
Four separate postgres() clients were open simultaneously (app, timer,
snapshots, socket), each defaulting to 10 connections, exhausting the
database's max_connections limit. Replaced with a single shared lazy-
initialized client in server/db.ts using a Proxy to defer the
DATABASE_URL check until first use (preserving test compatibility).
Also bumps the CS2 Champions Stage stochastic test from 200 → 1000
iterations to eliminate flakiness.
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Fix and() bug and add Swiss loop safety guard
- cs2-major-stage.ts: markCs2StageEliminations and setCs2FinalPlacements
were using JS && instead of Drizzle and(), causing WHERE to filter only
by participantId (not scoringEventId), which would update rows across
all events instead of just the target event
- cs-major-simulator.ts: add break guard in simulateSwiss while loop to
prevent infinite loop if pairGroups returns no pairs
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Fix all remaining code review issues
- cs2-major-stage.ts: use schema column reference for stageEliminated
in markCs2StageEliminations instead of raw SQL string
- cs-major-simulator.ts: simulateOneMajor now locks in known stage
results when a stage is complete (8 recorded eliminations), only
simulating the remaining stages during live events
- admin event page: add CS2 Stage Setup button for cs2_major_qualifying_points
simulator types; expose simulatorType in server loader type cast
- cs2-setup.tsx: replace document.getElementById DOM manipulation with
React state (eliminatedChecked map) for checkbox show/hide logic;
remove unused stageMap and unassignedParticipants variables
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Fix oxlint errors: non-null assertions, sort→toSorted, unused vars
- cs-major-simulator.ts: replace 5 non-null assertions (!) with safe
optional chaining / if-guards; replace 6 .sort() with .toSorted()
- cs2-major-stage.ts: remove unused `inArray` import
- cs2-setup.tsx: remove unused `assignedIds` variable
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Fix flaky Champions Stage stochastic test
The makeTeams(8) helper creates only a 70-pt Elo spread (1800→1730).
With the Champions Stage bracket math this gives team-0 a ~19.6% win
rate — right at the 0.2 threshold, causing the test to fail ~63% of
the time in CI despite 1000 iterations.
Use 100-pt steps (1800→1100) instead, giving team-0 a ~40% win rate
and raising the assertion threshold to 0.25 for a clear safety margin.
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-04-05 13:40:05 -07:00
|
|
|
|
"cs2_major_qualifying_points",
|
Add NCAA Football CFP simulator (12-team bracket) (#278)
Fixes #124
* Add NCAA Football CFP simulator (12-team bracket)
Implements a Monte Carlo simulator for the College Football Playoff using
the 2024-present 12-team format. Elo/FPI ratings are entered manually via
the existing admin Elo Ratings page; championship futures odds can
optionally be blended in (60% Elo / 40% odds).
- Add CFP_12 bracket template (First Round not scoring, QFs onward score)
- Add generateCFP12Bracket() with correct seeding: 5v12, 6v11, 7v10, 8v9
in First Round; seeds 1–4 receive QF byes
- Add NCAAFootballSimulator: 50k Monte Carlo sims, seeds teams by blended
Elo+odds strength, tracks champion/finalist/SF/QF placement tiers
- Register ncaa_football_bracket simulator type in registry and schema enum
- Add migration 0071: ALTER TYPE simulator_type ADD VALUE 'ncaa_football_bracket'
- Add tests: 30 tests covering bracket template structure and simulator
probability distributions, seeding, edge cases, futures blending
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix lint errors in NCAA Football CFP simulator
Replace non-null assertions with optional chaining, change let to const,
use toSorted() instead of sort(), and add a bump() helper to avoid
repeated map lookups with non-null assertions in simulateBracket.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix TS2345 in NCAA football simulator test
Add ?? 0 fallback so optional-chained probFirst is number, not number | undefined.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-08 09:48:32 -04:00
|
|
|
|
"ncaa_football_bracket",
|
2026-04-08 16:52:10 -04:00
|
|
|
|
"llws_bracket",
|
2026-03-09 15:34:31 -07:00
|
|
|
|
]);
|
|
|
|
|
|
|
Add playoff match game scheduling and odds management (#135)
* Add playoff match games and odds storage
Introduces two new tables for bracket matchup detail storage:
- `playoff_match_games`: tracks individual game schedules within a
series matchup (game number, scheduledAt, status, per-game scores,
winner). Supports scheduled/complete/postponed status enum.
- `playoff_match_odds`: stores moneyline odds per participant per
matchup (single upsert record, no isLatest complexity).
Includes:
- Drizzle schema + relations with CASCADE deletes from playoff_matches
- Migration 0040_fat_puma.sql
- playoff-match-game.ts model with pure helpers: computeSeriesScore,
isSeriesComplete, getSeriesLeader — plus full CRUD
- playoff-match-odds.ts model with pure helpers: americanToImpliedProbability,
impliedProbabilityToAmerican, normalizeOdds — plus upsert/read/delete
- findPlayoffMatchesByEventId and findPlayoffMatchById updated to
include games and odds in their query results
- Bracket server route: add-game, update-game, delete-game,
upsert-odds, delete-odds actions
- Bracket admin UI: expandable per-match panel for game schedule
management and moneyline odds entry
- 41 new unit tests (18 game + 23 odds), all 810 tests passing
https://claude.ai/code/session_01Twt3D1bsEK3eXUhMaz6ee7
* Code review fixes: type safety, abstraction, and React correctness
- Derive PlayoffMatchGameStatus from schema enum instead of hardcoding
the string union, eliminating the duplicate source of truth
- updateGame now returns PlayoffMatchGame | undefined to reflect reality
when no row matches the ID
- Remove TOCTOU check-then-act in update-game action: call updateGame
directly and check the return value instead of a pre-flight findGameById
- Add status enum validation before the cast in update-game action
- Move impliedProbability computation inside upsertMatchOdds so callers
only provide moneylineOdds; the model owns the derivation
- Remove unnecessary dynamic import of americanToImpliedProbability in
the upsert-odds action (was already imported from the same module)
- Fix React list reconciliation bug: replace bare <> fragment with
<Fragment key={match.id}> so React can correctly track rows
https://claude.ai/code/session_01Twt3D1bsEK3eXUhMaz6ee7
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-11 14:17:43 -07:00
|
|
|
|
export const playoffMatchGameStatusEnum = pgEnum("playoff_match_game_status", [
|
|
|
|
|
|
"scheduled",
|
|
|
|
|
|
"complete",
|
|
|
|
|
|
"postponed",
|
|
|
|
|
|
]);
|
|
|
|
|
|
|
2025-10-11 00:07:39 -07:00
|
|
|
|
export const leagues = pgTable("leagues", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
name: varchar("name", { length: 255 }).notNull(),
|
2026-04-29 10:03:50 -07:00
|
|
|
|
createdBy: varchar("created_by", { length: 255 }).notNull(), // UUID → users.id
|
2025-10-11 21:10:01 -07:00
|
|
|
|
currentSeasonId: uuid("current_season_id"), // References the active season
|
2025-10-20 15:03:11 -07:00
|
|
|
|
isPublicDraftBoard: boolean("is_public_draft_board").notNull().default(false),
|
2026-03-17 11:16:36 -07:00
|
|
|
|
discordWebhookUrl: text("discord_webhook_url"),
|
2025-10-11 00:07:39 -07:00
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
2025-10-12 21:16:00 -07:00
|
|
|
|
export const seasonTemplates = pgTable("season_templates", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
name: varchar("name", { length: 255 }).notNull(),
|
|
|
|
|
|
description: text("description"),
|
|
|
|
|
|
year: integer("year").notNull(),
|
|
|
|
|
|
isActive: boolean("is_active").notNull().default(true),
|
|
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
2025-10-11 00:07:39 -07:00
|
|
|
|
export const seasons = pgTable("seasons", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
leagueId: uuid("league_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => leagues.id, { onDelete: "cascade" }),
|
|
|
|
|
|
year: integer("year").notNull(),
|
|
|
|
|
|
status: seasonStatusEnum("status").notNull().default("pre_draft"),
|
2025-10-12 21:16:00 -07:00
|
|
|
|
templateId: uuid("template_id")
|
|
|
|
|
|
.references(() => seasonTemplates.id, { onDelete: "set null" }),
|
2025-10-15 21:50:02 -07:00
|
|
|
|
draftRounds: integer("draft_rounds").notNull().default(20),
|
2025-10-12 21:16:00 -07:00
|
|
|
|
flexSpots: integer("flex_spots").notNull().default(0),
|
2025-10-15 22:02:21 -07:00
|
|
|
|
draftDateTime: timestamp("draft_date_time"),
|
2025-10-16 00:32:48 -07:00
|
|
|
|
draftInitialTime: integer("draft_initial_time").notNull().default(120), // seconds
|
|
|
|
|
|
draftIncrementTime: integer("draft_increment_time").notNull().default(30), // seconds
|
2026-03-20 21:36:39 -07:00
|
|
|
|
draftTimerMode: draftTimerModeEnum("draft_timer_mode").notNull().default("chess_clock"),
|
2025-10-16 00:32:48 -07:00
|
|
|
|
currentPickNumber: integer("current_pick_number").default(1),
|
|
|
|
|
|
draftStartedAt: timestamp("draft_started_at"),
|
|
|
|
|
|
draftPaused: boolean("draft_paused").notNull().default(false),
|
2026-04-26 22:31:52 -07:00
|
|
|
|
overnightPauseMode: overnightPauseModeEnum("overnight_pause_mode").notNull().default("none"),
|
|
|
|
|
|
overnightPauseStart: varchar("overnight_pause_start", { length: 5 }), // "23:00"
|
|
|
|
|
|
overnightPauseEnd: varchar("overnight_pause_end", { length: 5 }), // "07:00"
|
|
|
|
|
|
overnightPauseTimezone: varchar("overnight_pause_timezone", { length: 50 }), // IANA — league TZ (league mode) or per-user fallback
|
2025-10-14 12:20:36 -07:00
|
|
|
|
inviteCode: varchar("invite_code", { length: 20 }).notNull().unique(),
|
2025-10-28 23:39:34 -07:00
|
|
|
|
// Scoring configuration (8 values for 1st through 8th)
|
|
|
|
|
|
pointsFor1st: integer("points_for_1st").notNull().default(100),
|
|
|
|
|
|
pointsFor2nd: integer("points_for_2nd").notNull().default(70),
|
|
|
|
|
|
pointsFor3rd: integer("points_for_3rd").notNull().default(50),
|
|
|
|
|
|
pointsFor4th: integer("points_for_4th").notNull().default(40),
|
|
|
|
|
|
pointsFor5th: integer("points_for_5th").notNull().default(25),
|
|
|
|
|
|
pointsFor6th: integer("points_for_6th").notNull().default(25),
|
|
|
|
|
|
pointsFor7th: integer("points_for_7th").notNull().default(15),
|
|
|
|
|
|
pointsFor8th: integer("points_for_8th").notNull().default(15),
|
2025-10-11 00:07:39 -07:00
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
export const teams = pgTable("teams", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
seasonId: uuid("season_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => seasons.id, { onDelete: "cascade" }),
|
|
|
|
|
|
name: varchar("name", { length: 255 }).notNull(),
|
2025-10-14 22:04:37 -07:00
|
|
|
|
logoUrl: varchar("logo_url", { length: 512 }),
|
2026-04-29 10:03:50 -07:00
|
|
|
|
ownerId: varchar("owner_id", { length: 255 }), // UUID → users.id, nullable
|
2025-10-11 00:07:39 -07:00
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
2025-10-11 00:29:04 -07:00
|
|
|
|
|
2025-10-15 08:58:35 -07:00
|
|
|
|
export const draftSlots = pgTable("draft_slots", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
seasonId: uuid("season_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => seasons.id, { onDelete: "cascade" }),
|
|
|
|
|
|
teamId: uuid("team_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => teams.id, { onDelete: "cascade" }),
|
|
|
|
|
|
draftOrder: integer("draft_order").notNull(),
|
|
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
2025-10-16 00:32:48 -07:00
|
|
|
|
export const draftPicks = pgTable("draft_picks", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
seasonId: uuid("season_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => seasons.id, { onDelete: "cascade" }),
|
|
|
|
|
|
teamId: uuid("team_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => teams.id, { onDelete: "cascade" }),
|
|
|
|
|
|
participantId: uuid("participant_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => participants.id, { onDelete: "cascade" }),
|
|
|
|
|
|
pickNumber: integer("pick_number").notNull(),
|
|
|
|
|
|
round: integer("round").notNull(),
|
|
|
|
|
|
pickInRound: integer("pick_in_round").notNull(),
|
2026-04-29 10:03:50 -07:00
|
|
|
|
pickedByUserId: varchar("picked_by_user_id", { length: 255 }).notNull(), // UUID → users.id
|
2025-10-16 00:32:48 -07:00
|
|
|
|
pickedByType: pickedByTypeEnum("picked_by_type").notNull(),
|
2026-02-23 23:23:24 -08:00
|
|
|
|
timeUsed: integer("time_used").notNull().default(0), // team's time bank (seconds) at the moment the pick was made
|
2025-10-16 00:32:48 -07:00
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
2026-02-23 23:23:24 -08:00
|
|
|
|
}, (t) => ({
|
|
|
|
|
|
// Prevents two concurrent picks from landing in the same slot
|
|
|
|
|
|
uniquePickSlot: uniqueIndex("draft_picks_season_pick_unique").on(t.seasonId, t.pickNumber),
|
|
|
|
|
|
}));
|
2025-10-16 00:32:48 -07:00
|
|
|
|
|
|
|
|
|
|
export const draftQueue = pgTable("draft_queue", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
seasonId: uuid("season_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => seasons.id, { onDelete: "cascade" }),
|
|
|
|
|
|
teamId: uuid("team_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => teams.id, { onDelete: "cascade" }),
|
|
|
|
|
|
participantId: uuid("participant_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => participants.id, { onDelete: "cascade" }),
|
|
|
|
|
|
queuePosition: integer("queue_position").notNull(),
|
|
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
export const draftTimers = pgTable("draft_timers", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
seasonId: uuid("season_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => seasons.id, { onDelete: "cascade" }),
|
|
|
|
|
|
teamId: uuid("team_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => teams.id, { onDelete: "cascade" }),
|
|
|
|
|
|
timeRemaining: integer("time_remaining").notNull(), // seconds
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
2025-10-21 23:22:17 -07:00
|
|
|
|
export const autodraftSettings = pgTable("autodraft_settings", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
seasonId: uuid("season_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => seasons.id, { onDelete: "cascade" }),
|
|
|
|
|
|
teamId: uuid("team_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => teams.id, { onDelete: "cascade" }),
|
|
|
|
|
|
isEnabled: boolean("is_enabled").notNull().default(false),
|
|
|
|
|
|
mode: autodraftModeEnum("mode").notNull().default("next_pick"),
|
Claude/redesign autodraft queue c4 kp r (#40)
* Redesign autodraft queue system with three-state control and queue-only constraint
Core Logic & Database:
- Add `queue_only` boolean column to `autodraft_settings` (migration 0031)
- Rename autodraft UI states: Off / Next Pick / All Picks (while_on mode maps to All Picks)
- `autoPickForTeam`: respects new `queueOnly` param — skips EV fallback when enabled
- `executeAutoPick`: auto-disables autodraft + emits socket event when queue empties with queueOnly ON (AC3)
- `autodraft-updated` socket event now includes `queueOnly` field
Mobile UI Overhaul:
- Rename "Lobby" tab → "Available" (AC6)
- Add new "Queue" tab to mobile bottom nav with drag-reorder, per-item Draft buttons, and autodraft controls (AC5)
- Controls tab retains commissioner tools, notifications, exit; queue controls moved to Queue tab
- Turn indicator appears on both Available and Queue tabs
Components:
- `AutodraftSettings`: replaces toggle+radio with three-state button group (Off | Next Pick | All Picks) + "Only autodraft from queue" switch (AC1, AC2)
- `QueueSection`: adds `canPick` prop + per-item Draft buttons for instant drafting when on the clock
Desktop (AC4):
- Sidebar QueueSection unchanged in position; gains same three-state controls and Draft buttons
Tests (AC7):
- `autodraft.test.ts`: updated for queueOnly field and socket event shape
- `timer-autodraft.test.ts`: new tests for queue-only constraint, auto-shutoff transitions, and all three autodraft states
https://claude.ai/code/session_01PYhJicAStoJ2u6q6dV1naB
* fix: remove erroneous ?? fallbacks in autodraft socket emissions and add autoPickForTeam tests
- Remove `?? true` default on queueOnly in queue-empty auto-disable socket emit
(line 488) — was dead code since the column is NOT NULL, but semantically wrong
and would have caused client-side UI desync if the type ever relaxed
- Remove `?? false` default on the next_pick auto-disable path for consistency
- Add app/models/__tests__/auto-pick.test.ts with 6 tests covering the queueOnly
constraint: empty queue, all items drafted, partial queue skip, and EV fallback
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix: add missing queueOnly prop to AutodraftSettings test fixtures
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* test: rewrite AutodraftSettings tests for three-state button group UI
The component was redesigned from a switch + radio buttons to Off/Next Pick/All Picks
buttons with a separate queue-only Switch toggle. Updated 17 stale tests and added 5
new tests covering the queue-only toggle and the All Picks/Off button interactions.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-02-27 22:16:26 -08:00
|
|
|
|
queueOnly: boolean("queue_only").notNull().default(false),
|
2025-10-21 23:22:17 -07:00
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
2025-10-11 00:29:04 -07:00
|
|
|
|
export const commissioners = pgTable("commissioners", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
leagueId: uuid("league_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => leagues.id, { onDelete: "cascade" }),
|
2026-04-29 10:03:50 -07:00
|
|
|
|
userId: varchar("user_id", { length: 255 }).notNull(), // UUID → users.id
|
2025-10-11 00:29:04 -07:00
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
2025-10-12 21:16:00 -07:00
|
|
|
|
|
|
|
|
|
|
// Sports Tables
|
|
|
|
|
|
export const sports = pgTable("sports", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
name: varchar("name", { length: 255 }).notNull(),
|
|
|
|
|
|
type: sportTypeEnum("type").notNull(),
|
|
|
|
|
|
slug: varchar("slug", { length: 255 }).notNull().unique(),
|
|
|
|
|
|
description: text("description"),
|
2025-10-13 10:30:47 -07:00
|
|
|
|
iconUrl: varchar("icon_url", { length: 255 }), // Filename of icon in /public/sports-icons/
|
2026-03-09 15:34:31 -07:00
|
|
|
|
simulatorType: simulatorTypeEnum("simulator_type"),
|
2025-10-12 21:16:00 -07:00
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
export const sportsSeasons = pgTable("sports_seasons", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
sportId: uuid("sport_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => sports.id, { onDelete: "cascade" }),
|
|
|
|
|
|
name: varchar("name", { length: 255 }).notNull(),
|
|
|
|
|
|
year: integer("year").notNull(),
|
|
|
|
|
|
startDate: date("start_date"),
|
|
|
|
|
|
endDate: date("end_date"),
|
|
|
|
|
|
status: sportsSeasonStatusEnum("status").notNull().default("upcoming"),
|
|
|
|
|
|
scoringType: scoringTypeEnum("scoring_type").notNull(),
|
2025-10-28 23:39:34 -07:00
|
|
|
|
// New scoring pattern field (replaces/augments scoringType)
|
|
|
|
|
|
scoringPattern: scoringPatternEnum("scoring_pattern"),
|
|
|
|
|
|
// For qualifying points sports
|
|
|
|
|
|
totalMajors: integer("total_majors"),
|
|
|
|
|
|
majorsCompleted: integer("majors_completed").notNull().default(0),
|
|
|
|
|
|
qualifyingPointsFinalized: boolean("qualifying_points_finalized").notNull().default(false),
|
2025-11-17 22:19:46 -08:00
|
|
|
|
// EV Calibration parameters (for Elo-based probability generation)
|
|
|
|
|
|
eloCalibrationExponent: decimal("elo_calibration_exponent", { precision: 3, scale: 2 }), // e.g., 0.33
|
|
|
|
|
|
eloMinRating: integer("elo_min_rating").default(1250),
|
|
|
|
|
|
eloMaxRating: integer("elo_max_rating").default(1750),
|
2026-03-09 15:34:31 -07:00
|
|
|
|
// Simulation status (prevents concurrent simulation runs)
|
|
|
|
|
|
simulationStatus: simulationStatusEnum("simulation_status").notNull().default("idle"),
|
2026-04-05 19:09:52 -07:00
|
|
|
|
// Controls the window during which this sport season appears in league creation/settings
|
|
|
|
|
|
draftOn: date("draft_on").notNull(),
|
|
|
|
|
|
draftOff: date("draft_off").notNull(),
|
2025-10-12 21:16:00 -07:00
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
export const participants = pgTable("participants", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
sportsSeasonId: uuid("sports_season_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => sportsSeasons.id, { onDelete: "cascade" }),
|
|
|
|
|
|
name: varchar("name", { length: 255 }).notNull(),
|
|
|
|
|
|
shortName: varchar("short_name", { length: 100 }),
|
|
|
|
|
|
externalId: varchar("external_id", { length: 255 }),
|
2026-03-09 15:34:31 -07:00
|
|
|
|
expectedValue: decimal("expected_value", { precision: 10, scale: 4 }).notNull().default("0"),
|
2026-04-09 01:57:22 +00:00
|
|
|
|
vorpValue: decimal("vorp_value", { precision: 10, scale: 4 }).notNull().default("0"),
|
2025-10-12 21:16:00 -07:00
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
2026-03-27 01:09:04 -07:00
|
|
|
|
}, (table) => [
|
|
|
|
|
|
uniqueIndex("participants_sports_season_name_unique").on(table.sportsSeasonId, table.name),
|
|
|
|
|
|
]);
|
2025-10-12 21:16:00 -07:00
|
|
|
|
|
|
|
|
|
|
export const seasonTemplateSports = pgTable("season_template_sports", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
templateId: uuid("template_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => seasonTemplates.id, { onDelete: "cascade" }),
|
|
|
|
|
|
sportsSeasonId: uuid("sports_season_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => sportsSeasons.id, { onDelete: "cascade" }),
|
|
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
export const seasonSports = pgTable("season_sports", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
seasonId: uuid("season_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => seasons.id, { onDelete: "cascade" }),
|
|
|
|
|
|
sportsSeasonId: uuid("sports_season_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => sportsSeasons.id, { onDelete: "cascade" }),
|
|
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
export const participantResults = pgTable("participant_results", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
participantId: uuid("participant_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => participants.id, { onDelete: "cascade" }),
|
|
|
|
|
|
sportsSeasonId: uuid("sports_season_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => sportsSeasons.id, { onDelete: "cascade" }),
|
|
|
|
|
|
finalPosition: integer("final_position"),
|
2026-03-10 10:27:58 -07:00
|
|
|
|
isPartialScore: boolean("is_partial_score").notNull().default(false),
|
2025-10-12 21:16:00 -07:00
|
|
|
|
qualifyingPoints: decimal("qualifying_points", { precision: 10, scale: 2 }),
|
|
|
|
|
|
notes: text("notes"),
|
|
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
2025-10-28 23:39:34 -07:00
|
|
|
|
// Scoring System Tables
|
|
|
|
|
|
|
|
|
|
|
|
// Individual scoring events (games, tournaments, races)
|
|
|
|
|
|
export const scoringEvents = pgTable("scoring_events", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
sportsSeasonId: uuid("sports_season_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => sportsSeasons.id, { onDelete: "cascade" }),
|
|
|
|
|
|
name: varchar("name", { length: 255 }).notNull(), // "2024 Masters", "Super Bowl LIX", etc.
|
|
|
|
|
|
eventDate: date("event_date"),
|
2026-03-15 10:22:42 -07:00
|
|
|
|
eventStartsAt: timestamp("event_starts_at", { withTimezone: true }),
|
2025-10-28 23:39:34 -07:00
|
|
|
|
eventType: eventTypeEnum("event_type").notNull(),
|
|
|
|
|
|
// For playoff events
|
|
|
|
|
|
playoffRound: varchar("playoff_round", { length: 50 }), // "Quarterfinals", "Semifinals", "Finals"
|
|
|
|
|
|
// For qualifying events
|
|
|
|
|
|
isQualifyingEvent: boolean("is_qualifying_event").notNull().default(false),
|
2025-11-03 13:16:37 -08:00
|
|
|
|
// Template system (Phase 2.6)
|
|
|
|
|
|
bracketTemplateId: varchar("bracket_template_id", { length: 50 }), // "ncaa_68", "nfl_14", "simple_16", etc.
|
|
|
|
|
|
scoringStartsAtRound: varchar("scoring_starts_at_round", { length: 50 }), // "Elite Eight", "Quarterfinals", etc.
|
2026-03-15 21:52:47 -07:00
|
|
|
|
// Per-event region config for NCAA-style brackets (overrides template defaults)
|
|
|
|
|
|
bracketRegionConfig: jsonb("bracket_region_config"), // BracketRegion[] | null
|
2025-10-28 23:39:34 -07:00
|
|
|
|
isComplete: boolean("is_complete").notNull().default(false),
|
|
|
|
|
|
completedAt: timestamp("completed_at"),
|
|
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
// Results for participants in specific events
|
|
|
|
|
|
export const eventResults = pgTable("event_results", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
scoringEventId: uuid("scoring_event_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => scoringEvents.id, { onDelete: "cascade" }),
|
|
|
|
|
|
participantId: uuid("participant_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => participants.id, { onDelete: "cascade" }),
|
|
|
|
|
|
// Placement in this specific event
|
|
|
|
|
|
placement: integer("placement"),
|
|
|
|
|
|
// For qualifying events: QP awarded in this event
|
|
|
|
|
|
qualifyingPointsAwarded: decimal("qualifying_points_awarded", { precision: 10, scale: 2 }),
|
|
|
|
|
|
// For playoff events: eliminated or advanced
|
|
|
|
|
|
eliminated: boolean("eliminated"),
|
|
|
|
|
|
// Raw sport-specific data (optional)
|
|
|
|
|
|
rawScore: decimal("raw_score", { precision: 10, scale: 2 }), // strokes, points, time, etc.
|
|
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
// Playoff bracket matches (for display and tracking)
|
|
|
|
|
|
export const playoffMatches = pgTable("playoff_matches", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
scoringEventId: uuid("scoring_event_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => scoringEvents.id, { onDelete: "cascade" }),
|
|
|
|
|
|
round: varchar("round", { length: 50 }).notNull(), // "Quarterfinals", "Semifinals", "Finals"
|
|
|
|
|
|
matchNumber: integer("match_number").notNull(), // 1, 2, 3, 4 (for QF); 1, 2 (for SF); 1 (for F)
|
|
|
|
|
|
participant1Id: uuid("participant1_id").references(() => participants.id, { onDelete: "set null" }),
|
|
|
|
|
|
participant2Id: uuid("participant2_id").references(() => participants.id, { onDelete: "set null" }),
|
|
|
|
|
|
winnerId: uuid("winner_id").references(() => participants.id, { onDelete: "set null" }),
|
|
|
|
|
|
loserId: uuid("loser_id").references(() => participants.id, { onDelete: "set null" }),
|
|
|
|
|
|
isComplete: boolean("is_complete").notNull().default(false),
|
|
|
|
|
|
// Optional detailed data
|
|
|
|
|
|
participant1Score: decimal("participant1_score", { precision: 10, scale: 2 }),
|
|
|
|
|
|
participant2Score: decimal("participant2_score", { precision: 10, scale: 2 }),
|
2025-11-03 13:16:37 -08:00
|
|
|
|
// Template system (Phase 2.6)
|
|
|
|
|
|
isScoring: boolean("is_scoring").notNull().default(true), // Does this match affect fantasy points?
|
|
|
|
|
|
templateRound: varchar("template_round", { length: 50 }), // "First Four", "Round of 64", "Elite Eight", etc.
|
|
|
|
|
|
seedInfo: varchar("seed_info", { length: 50 }), // "1 vs 16", "11a vs 11b", etc. (for display)
|
2025-10-28 23:39:34 -07:00
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
Add playoff match game scheduling and odds management (#135)
* Add playoff match games and odds storage
Introduces two new tables for bracket matchup detail storage:
- `playoff_match_games`: tracks individual game schedules within a
series matchup (game number, scheduledAt, status, per-game scores,
winner). Supports scheduled/complete/postponed status enum.
- `playoff_match_odds`: stores moneyline odds per participant per
matchup (single upsert record, no isLatest complexity).
Includes:
- Drizzle schema + relations with CASCADE deletes from playoff_matches
- Migration 0040_fat_puma.sql
- playoff-match-game.ts model with pure helpers: computeSeriesScore,
isSeriesComplete, getSeriesLeader — plus full CRUD
- playoff-match-odds.ts model with pure helpers: americanToImpliedProbability,
impliedProbabilityToAmerican, normalizeOdds — plus upsert/read/delete
- findPlayoffMatchesByEventId and findPlayoffMatchById updated to
include games and odds in their query results
- Bracket server route: add-game, update-game, delete-game,
upsert-odds, delete-odds actions
- Bracket admin UI: expandable per-match panel for game schedule
management and moneyline odds entry
- 41 new unit tests (18 game + 23 odds), all 810 tests passing
https://claude.ai/code/session_01Twt3D1bsEK3eXUhMaz6ee7
* Code review fixes: type safety, abstraction, and React correctness
- Derive PlayoffMatchGameStatus from schema enum instead of hardcoding
the string union, eliminating the duplicate source of truth
- updateGame now returns PlayoffMatchGame | undefined to reflect reality
when no row matches the ID
- Remove TOCTOU check-then-act in update-game action: call updateGame
directly and check the return value instead of a pre-flight findGameById
- Add status enum validation before the cast in update-game action
- Move impliedProbability computation inside upsertMatchOdds so callers
only provide moneylineOdds; the model owns the derivation
- Remove unnecessary dynamic import of americanToImpliedProbability in
the upsert-odds action (was already imported from the same module)
- Fix React list reconciliation bug: replace bare <> fragment with
<Fragment key={match.id}> so React can correctly track rows
https://claude.ai/code/session_01Twt3D1bsEK3eXUhMaz6ee7
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-11 14:17:43 -07:00
|
|
|
|
// Individual games within a playoff matchup (e.g., NBA 7-game series games)
|
|
|
|
|
|
export const playoffMatchGames = pgTable("playoff_match_games", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
playoffMatchId: uuid("playoff_match_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => playoffMatches.id, { onDelete: "cascade" }),
|
|
|
|
|
|
gameNumber: integer("game_number").notNull(),
|
|
|
|
|
|
scheduledAt: timestamp("scheduled_at"),
|
|
|
|
|
|
status: playoffMatchGameStatusEnum("status").notNull().default("scheduled"),
|
|
|
|
|
|
participant1Score: decimal("participant1_score", { precision: 10, scale: 2 }),
|
|
|
|
|
|
participant2Score: decimal("participant2_score", { precision: 10, scale: 2 }),
|
|
|
|
|
|
winnerId: uuid("winner_id").references(() => participants.id, { onDelete: "set null" }),
|
|
|
|
|
|
notes: text("notes"),
|
|
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
// Moneyline odds per participant per matchup (single record per participant, overwritten on update)
|
|
|
|
|
|
export const playoffMatchOdds = pgTable("playoff_match_odds", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
playoffMatchId: uuid("playoff_match_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => playoffMatches.id, { onDelete: "cascade" }),
|
|
|
|
|
|
participantId: uuid("participant_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => participants.id, { onDelete: "cascade" }),
|
|
|
|
|
|
moneylineOdds: integer("moneyline_odds"), // American format e.g. -110, +150
|
|
|
|
|
|
impliedProbability: decimal("implied_probability", { precision: 6, scale: 4 }),
|
|
|
|
|
|
oddsSource: varchar("odds_source", { length: 100 }),
|
|
|
|
|
|
recordedAt: timestamp("recorded_at").defaultNow().notNull(),
|
|
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
2025-10-28 23:39:34 -07:00
|
|
|
|
// Aggregated participant qualifying points (for qualifying_points sports)
|
|
|
|
|
|
export const participantQualifyingTotals = pgTable("participant_qualifying_totals", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
participantId: uuid("participant_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => participants.id, { onDelete: "cascade" }),
|
|
|
|
|
|
sportsSeasonId: uuid("sports_season_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => sportsSeasons.id, { onDelete: "cascade" }),
|
|
|
|
|
|
totalQualifyingPoints: decimal("total_qualifying_points", { precision: 10, scale: 2 }).notNull().default("0"),
|
|
|
|
|
|
eventsScored: integer("events_scored").notNull().default(0),
|
|
|
|
|
|
// After finalization
|
|
|
|
|
|
finalRanking: integer("final_ranking"), // 1-8 based on QP totals
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
// Configurable qualifying point values per sports season
|
|
|
|
|
|
export const qualifyingPointConfig = pgTable("qualifying_point_config", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
sportsSeasonId: uuid("sports_season_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => sportsSeasons.id, { onDelete: "cascade" }),
|
|
|
|
|
|
placement: integer("placement").notNull(), // 1-16
|
|
|
|
|
|
points: decimal("points", { precision: 10, scale: 2 }).notNull(),
|
|
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
// Team scores aggregated by sport season
|
|
|
|
|
|
export const teamSportScores = pgTable("team_sport_scores", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
teamId: uuid("team_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => teams.id, { onDelete: "cascade" }),
|
|
|
|
|
|
sportsSeasonId: uuid("sports_season_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => sportsSeasons.id, { onDelete: "cascade" }),
|
|
|
|
|
|
totalPoints: decimal("total_points", { precision: 10, scale: 2 }).notNull().default("0"),
|
|
|
|
|
|
participantsCompleted: integer("participants_completed").notNull().default(0), // How many picks have finished
|
|
|
|
|
|
participantsTotal: integer("participants_total").notNull().default(0), // Total picks for this sport
|
|
|
|
|
|
calculatedAt: timestamp("calculated_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
// Overall team standings (snapshot-based for movement tracking)
|
|
|
|
|
|
export const teamStandings = pgTable("team_standings", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
teamId: uuid("team_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => teams.id, { onDelete: "cascade" }),
|
|
|
|
|
|
seasonId: uuid("season_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => seasons.id, { onDelete: "cascade" }),
|
|
|
|
|
|
totalPoints: decimal("total_points", { precision: 10, scale: 2 }).notNull().default("0"),
|
|
|
|
|
|
currentRank: integer("current_rank").notNull(),
|
|
|
|
|
|
previousRank: integer("previous_rank"), // For movement indicators
|
|
|
|
|
|
// Tiebreaker data
|
|
|
|
|
|
firstPlaceCount: integer("first_place_count").notNull().default(0),
|
|
|
|
|
|
secondPlaceCount: integer("second_place_count").notNull().default(0),
|
|
|
|
|
|
thirdPlaceCount: integer("third_place_count").notNull().default(0),
|
|
|
|
|
|
fourthPlaceCount: integer("fourth_place_count").notNull().default(0),
|
|
|
|
|
|
fifthPlaceCount: integer("fifth_place_count").notNull().default(0),
|
|
|
|
|
|
sixthPlaceCount: integer("sixth_place_count").notNull().default(0),
|
|
|
|
|
|
seventhPlaceCount: integer("seventh_place_count").notNull().default(0),
|
|
|
|
|
|
eighthPlaceCount: integer("eighth_place_count").notNull().default(0),
|
|
|
|
|
|
participantsRemaining: integer("participants_remaining").notNull().default(0), // Not yet finished
|
2026-02-14 22:30:12 -08:00
|
|
|
|
// Expected value tracking (Phase 5.4)
|
|
|
|
|
|
actualPoints: decimal("actual_points", { precision: 10, scale: 2 }), // Points from finished participants
|
|
|
|
|
|
projectedPoints: decimal("projected_points", { precision: 10, scale: 2 }), // actualPoints + EVs of unfinished
|
|
|
|
|
|
participantsFinished: integer("participants_finished"), // Count of finished participants
|
2025-10-28 23:39:34 -07:00
|
|
|
|
calculatedAt: timestamp("calculated_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
// Daily standings snapshots for historical tracking
|
|
|
|
|
|
export const teamStandingsSnapshots = pgTable("team_standings_snapshots", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
teamId: uuid("team_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => teams.id, { onDelete: "cascade" }),
|
|
|
|
|
|
seasonId: uuid("season_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => seasons.id, { onDelete: "cascade" }),
|
|
|
|
|
|
snapshotDate: date("snapshot_date").notNull(),
|
|
|
|
|
|
totalPoints: decimal("total_points", { precision: 10, scale: 2 }).notNull().default("0"),
|
|
|
|
|
|
rank: integer("rank").notNull(),
|
|
|
|
|
|
// Tiebreaker data
|
|
|
|
|
|
firstPlaceCount: integer("first_place_count").notNull().default(0),
|
|
|
|
|
|
secondPlaceCount: integer("second_place_count").notNull().default(0),
|
|
|
|
|
|
thirdPlaceCount: integer("third_place_count").notNull().default(0),
|
|
|
|
|
|
fourthPlaceCount: integer("fourth_place_count").notNull().default(0),
|
|
|
|
|
|
fifthPlaceCount: integer("fifth_place_count").notNull().default(0),
|
|
|
|
|
|
sixthPlaceCount: integer("sixth_place_count").notNull().default(0),
|
|
|
|
|
|
seventhPlaceCount: integer("seventh_place_count").notNull().default(0),
|
|
|
|
|
|
eighthPlaceCount: integer("eighth_place_count").notNull().default(0),
|
|
|
|
|
|
participantsRemaining: integer("participants_remaining").notNull().default(0),
|
2025-11-17 22:19:46 -08:00
|
|
|
|
// Expected value tracking
|
|
|
|
|
|
actualPoints: decimal("actual_points", { precision: 10, scale: 2 }), // Points from finished participants
|
|
|
|
|
|
projectedPoints: decimal("projected_points", { precision: 10, scale: 2 }), // actualPoints + EVs of unfinished
|
|
|
|
|
|
participantsFinished: integer("participants_finished"), // Count of finished participants
|
2025-10-28 23:39:34 -07:00
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
2026-03-18 22:15:28 -07:00
|
|
|
|
}, (t) => ({
|
|
|
|
|
|
uniqueTeamSeasonDate: uniqueIndex("team_standings_snapshots_unique").on(
|
|
|
|
|
|
t.teamId, t.seasonId, t.snapshotDate
|
|
|
|
|
|
),
|
|
|
|
|
|
}));
|
2025-10-28 23:39:34 -07:00
|
|
|
|
|
2025-11-17 22:19:46 -08:00
|
|
|
|
// Expected value tracking (sports-season-specific)
|
2025-10-28 23:39:34 -07:00
|
|
|
|
export const participantExpectedValues = pgTable("participant_expected_values", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
participantId: uuid("participant_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => participants.id, { onDelete: "cascade" }),
|
2025-11-17 22:19:46 -08:00
|
|
|
|
sportsSeasonId: uuid("sports_season_id")
|
2025-10-28 23:39:34 -07:00
|
|
|
|
.notNull()
|
2025-11-17 22:19:46 -08:00
|
|
|
|
.references(() => sportsSeasons.id, { onDelete: "cascade" }),
|
2026-03-09 15:34:31 -07:00
|
|
|
|
// Probability distribution (stored as fractions, e.g. 0.1550 = 15.5%)
|
|
|
|
|
|
probFirst: decimal("prob_first", { precision: 6, scale: 4 }).notNull().default("0"),
|
|
|
|
|
|
probSecond: decimal("prob_second", { precision: 6, scale: 4 }).notNull().default("0"),
|
|
|
|
|
|
probThird: decimal("prob_third", { precision: 6, scale: 4 }).notNull().default("0"),
|
|
|
|
|
|
probFourth: decimal("prob_fourth", { precision: 6, scale: 4 }).notNull().default("0"),
|
|
|
|
|
|
probFifth: decimal("prob_fifth", { precision: 6, scale: 4 }).notNull().default("0"),
|
|
|
|
|
|
probSixth: decimal("prob_sixth", { precision: 6, scale: 4 }).notNull().default("0"),
|
|
|
|
|
|
probSeventh: decimal("prob_seventh", { precision: 6, scale: 4 }).notNull().default("0"),
|
|
|
|
|
|
probEighth: decimal("prob_eighth", { precision: 6, scale: 4 }).notNull().default("0"),
|
2025-10-28 23:39:34 -07:00
|
|
|
|
// Calculated EV
|
2026-03-09 15:34:31 -07:00
|
|
|
|
expectedValue: decimal("expected_value", { precision: 10, scale: 4 }).notNull().default("0"),
|
2025-11-17 22:19:46 -08:00
|
|
|
|
// Metadata
|
|
|
|
|
|
source: probabilitySourceEnum("source").default("manual"), // How probabilities were generated
|
|
|
|
|
|
sourceOdds: integer("source_odds"), // Original odds if source is futures_odds (American odds format)
|
Add PDC World Darts Championship simulator with Elo-based bracket (#248)
Fixes #123
* Add PDC World Darts Championship simulator (128-player bracket)
- New DartsSimulator: 128-player single-elimination, 7 rounds with
PDC-accurate best-of-sets formats (bo3/bo5/bo5/bo7/bo7/bo11/bo13).
ELO_DIVISOR=500 via set-level Bernoulli model. Two simulation paths:
Path A (bracket drawn) simulates from actual DB matches; Path B
(pre-bracket) seeds top 32 by world ranking in fixed positions and
randomly draws the remaining 96 per simulation run (50,000 iterations).
- darts_bracket added to simulatorTypeEnum and simulator registry.
- world_ranking nullable integer column added to participant_expected_values
(migration 0067); batchSaveSourceElos now accepts and persists it.
- Admin route /admin/sports-seasons/:id/darts-elo: bulk import with format
"Player Name, 2099, 1" (name, Elo, optional world ranking), fuzzy name
matching, auto-runs simulation and updates EV/snapshots on save.
- DARTS_128 bracket template added (scoring starts at Quarterfinals).
- 30 unit tests: math helpers, bracket seeding structure, Path A/B integration.
https://claude.ai/code/session_01WZ6FjMmC2eBeZ1564M9Ruz
* Review fixes: pre-compute hot-loop invariants, import normalizeName
- Pre-compute seededSlots and getSeededMatchOrder(32) before the 50k
simulation loop — was being recomputed every iteration
- Pad unseeded pool to 96 once before the loop instead of inside it
- Inline bracket-building in the hot loop using pre-computed seededSlots;
removes the per-iteration call to buildR1Bracket/getSeededMatchOrder
- Remove dead SEEDED_R1_PAIRS constant (was never referenced)
- Import normalizeName from ~/lib/fuzzy-match instead of redefining it locally
https://claude.ai/code/session_01WZ6FjMmC2eBeZ1564M9Ruz
* Fix lint failures: unused vars, eqeqeq, toSorted
- Remove unused seededSet/unseededSet variables in test
- Replace != null with !== null && !== undefined (eqeqeq rule)
- Replace .sort() with .toSorted() in simulator and route (unicorn/no-array-sort)
https://claude.ai/code/session_01WZ6FjMmC2eBeZ1564M9Ruz
* Fix TS2552: restore seededSet declaration removed during lint fix
https://claude.ai/code/session_01WZ6FjMmC2eBeZ1564M9Ruz
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-31 15:37:28 -07:00
|
|
|
|
sourceElo: integer("source_elo"), // Raw Elo rating if source is elo-based simulator (e.g. snooker_bracket, darts_bracket)
|
|
|
|
|
|
worldRanking: integer("world_ranking"), // World ranking for sports that use it for bracket seeding (e.g. darts_bracket)
|
2025-10-28 23:39:34 -07:00
|
|
|
|
calculatedAt: timestamp("calculated_at").defaultNow().notNull(),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
2026-03-23 08:24:28 -07:00
|
|
|
|
}, (t) => ({
|
|
|
|
|
|
uniqueParticipantSeason: uniqueIndex("participant_ev_participant_season_unique").on(
|
|
|
|
|
|
t.participantId, t.sportsSeasonId
|
|
|
|
|
|
),
|
|
|
|
|
|
}));
|
2025-10-28 23:39:34 -07:00
|
|
|
|
|
2026-02-14 22:30:12 -08:00
|
|
|
|
// Tournament group stage tables (for FIFA World Cup style tournaments)
|
|
|
|
|
|
export const tournamentGroups = pgTable("tournament_groups", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
scoringEventId: uuid("scoring_event_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => scoringEvents.id, { onDelete: "cascade" }),
|
|
|
|
|
|
groupName: varchar("group_name", { length: 10 }).notNull(), // "A" through "L"
|
|
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
export const tournamentGroupMembers = pgTable("tournament_group_members", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
tournamentGroupId: uuid("tournament_group_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => tournamentGroups.id, { onDelete: "cascade" }),
|
|
|
|
|
|
participantId: uuid("participant_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => participants.id, { onDelete: "cascade" }),
|
|
|
|
|
|
eliminated: boolean("eliminated").notNull().default(false),
|
|
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
Add FIFA World Cup 2026 support with group stage display and Monte Carlo simulator (#242)
* Add FIFA World Cup 2026 support with group stage display and Monte Carlo simulator, fixes #127
- New `groupStageMatches` table for recording group play results (W/D/L, scores, matchday, schedule)
- `computeGroupStandings()` model function: pts → GD → GF → name tiebreaker ordering
- `GroupStageStandings` component showing all 12 groups with standings table and manager column
- Admin bracket UI: group match score entry, per-group standings, "Recalculate Floors" action
- `WorldCupSimulator`: 50k Monte Carlo covering group stage + best-8 3rd-place + knockout + 3rd place game
- Fuzzy name matching for national team Elo lookup (exact → substring → word-overlap), warns on miss
- Partial group completion: completed matches replayed with real scores, remaining matches simulated
- Elo priority: admin-entered sourceElo > futures odds converted to Elo > hardcoded national team ratings
- `fifa_48` bracket template: added Third Place Game round with `loserFeedsInto` on Semifinals
- Scoring rules: distinct 3rd/4th place for `fifa_48` (not averaged), QF losers share 5th–8th equally
- Floor scoring: SF participants guaranteed 4th (provisional), finalized after 3rd place game
- `recalculate-floors` admin action deletes and replays all results from scratch (fixes stale guard bug)
- Unique index on `(tournamentGroupId, participant1Id, participant2Id)` to prevent duplicate pairings
- Batch `findMatchesByGroupIds()` replacing N sequential queries in the sport season loader
- League home mini-standings now shows `actualPoints` (includes floor) instead of `totalPoints` only
- Elo ratings admin page supports World Cup (same bulk-import flow as snooker)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix TypeScript errors: update GroupStandingData type to use findMatchesByGroupIds
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Increase Node heap to 4GB for unit tests in CI to prevent OOM
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix OOM in CI: make WorldCupSimulator simulation count configurable for tests
Tests now pass numSimulations=500 instead of the production default of 50,000.
Six simulator tests × 50k iterations each was exhausting the 4GB heap on GitHub
Actions runners. Also reduce simGroupMatch stat tests from 50k to 5k iterations.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-29 10:27:47 -07:00
|
|
|
|
export const groupStageMatches = pgTable("group_stage_matches", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
tournamentGroupId: uuid("tournament_group_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => tournamentGroups.id, { onDelete: "cascade" }),
|
|
|
|
|
|
participant1Id: uuid("participant1_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => participants.id),
|
|
|
|
|
|
participant2Id: uuid("participant2_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => participants.id),
|
|
|
|
|
|
participant1Score: integer("participant1_score"),
|
|
|
|
|
|
participant2Score: integer("participant2_score"),
|
|
|
|
|
|
isComplete: boolean("is_complete").notNull().default(false),
|
|
|
|
|
|
matchday: integer("matchday").notNull(), // 1, 2, or 3 (round of group play)
|
|
|
|
|
|
scheduledAt: timestamp("scheduled_at"),
|
|
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
}, (t) => [
|
|
|
|
|
|
// Prevent duplicate pairings within the same group (order-independent)
|
|
|
|
|
|
uniqueIndex("group_stage_matches_group_pair_unique")
|
|
|
|
|
|
.on(t.tournamentGroupId, t.participant1Id, t.participant2Id),
|
|
|
|
|
|
]);
|
|
|
|
|
|
|
2025-10-28 23:39:34 -07:00
|
|
|
|
// Participant season results (for F1 current points tracking during season)
|
|
|
|
|
|
export const participantSeasonResults = pgTable("participant_season_results", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
participantId: uuid("participant_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => participants.id, { onDelete: "cascade" }),
|
|
|
|
|
|
sportsSeasonId: uuid("sports_season_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => sportsSeasons.id, { onDelete: "cascade" }),
|
|
|
|
|
|
currentPoints: decimal("current_points", { precision: 10, scale: 2 }).notNull().default("0"), // Current F1 championship points, etc.
|
|
|
|
|
|
currentPosition: integer("current_position"), // Current standings position
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
2026-03-09 15:34:31 -07:00
|
|
|
|
// EV snapshots — historical record of participant EV over time (one per participant per sport season per day)
|
|
|
|
|
|
export const participantEvSnapshots = pgTable("participant_ev_snapshots", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
participantId: uuid("participant_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => participants.id, { onDelete: "cascade" }),
|
|
|
|
|
|
sportsSeasonId: uuid("sports_season_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => sportsSeasons.id, { onDelete: "cascade" }),
|
|
|
|
|
|
snapshotDate: date("snapshot_date").notNull(),
|
|
|
|
|
|
// Probability distribution (stored as fractions, e.g. 0.1550 = 15.5%)
|
|
|
|
|
|
probFirst: decimal("prob_first", { precision: 5, scale: 2 }).notNull().default("0"),
|
|
|
|
|
|
probSecond: decimal("prob_second", { precision: 5, scale: 2 }).notNull().default("0"),
|
|
|
|
|
|
probThird: decimal("prob_third", { precision: 5, scale: 2 }).notNull().default("0"),
|
|
|
|
|
|
probFourth: decimal("prob_fourth", { precision: 5, scale: 2 }).notNull().default("0"),
|
|
|
|
|
|
probFifth: decimal("prob_fifth", { precision: 5, scale: 2 }).notNull().default("0"),
|
|
|
|
|
|
probSixth: decimal("prob_sixth", { precision: 5, scale: 2 }).notNull().default("0"),
|
|
|
|
|
|
probSeventh: decimal("prob_seventh", { precision: 5, scale: 2 }).notNull().default("0"),
|
|
|
|
|
|
probEighth: decimal("prob_eighth", { precision: 5, scale: 2 }).notNull().default("0"),
|
|
|
|
|
|
calculatedEV: decimal("calculated_ev", { precision: 10, scale: 4 }).notNull().default("0"),
|
|
|
|
|
|
source: varchar("source", { length: 100 }).notNull(), // e.g. 'bracket_monte_carlo', 'f1_standings_model'
|
|
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
}, (t) => ({
|
|
|
|
|
|
uniqueParticipantSeasonDate: uniqueIndex("participant_ev_snapshots_unique").on(
|
|
|
|
|
|
t.participantId, t.sportsSeasonId, t.snapshotDate
|
|
|
|
|
|
),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
// Team EV snapshots — historical projected points per team per fantasy season per day
|
|
|
|
|
|
export const teamEvSnapshots = pgTable("team_ev_snapshots", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
teamId: uuid("team_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => teams.id, { onDelete: "cascade" }),
|
|
|
|
|
|
seasonId: uuid("season_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => seasons.id, { onDelete: "cascade" }),
|
|
|
|
|
|
snapshotDate: date("snapshot_date").notNull(),
|
|
|
|
|
|
projectedPoints: decimal("projected_points", { precision: 10, scale: 2 }).notNull().default("0"),
|
|
|
|
|
|
actualPoints: decimal("actual_points", { precision: 10, scale: 2 }).notNull().default("0"),
|
|
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
}, (t) => ({
|
|
|
|
|
|
uniqueTeamSeasonDate: uniqueIndex("team_ev_snapshots_unique").on(
|
|
|
|
|
|
t.teamId, t.seasonId, t.snapshotDate
|
|
|
|
|
|
),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
2025-10-12 21:16:00 -07:00
|
|
|
|
// Relations
|
|
|
|
|
|
export const sportsRelations = relations(sports, ({ many }) => ({
|
|
|
|
|
|
sportsSeasons: many(sportsSeasons),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
export const sportsSeasonsRelations = relations(sportsSeasons, ({ one, many }) => ({
|
|
|
|
|
|
sport: one(sports, {
|
|
|
|
|
|
fields: [sportsSeasons.sportId],
|
|
|
|
|
|
references: [sports.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
participants: many(participants),
|
|
|
|
|
|
seasonTemplateSports: many(seasonTemplateSports),
|
|
|
|
|
|
seasonSports: many(seasonSports),
|
|
|
|
|
|
participantResults: many(participantResults),
|
2026-03-21 00:12:01 -07:00
|
|
|
|
regularSeasonStandings: many(regularSeasonStandings),
|
|
|
|
|
|
pendingStandingsMappings: many(pendingStandingsMappings),
|
2025-10-12 21:16:00 -07:00
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
export const participantsRelations = relations(participants, ({ one, many }) => ({
|
|
|
|
|
|
sportsSeason: one(sportsSeasons, {
|
|
|
|
|
|
fields: [participants.sportsSeasonId],
|
|
|
|
|
|
references: [sportsSeasons.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
results: many(participantResults),
|
2026-03-21 00:12:01 -07:00
|
|
|
|
regularSeasonStandings: many(regularSeasonStandings),
|
2025-10-12 21:16:00 -07:00
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
export const seasonTemplatesRelations = relations(seasonTemplates, ({ many }) => ({
|
|
|
|
|
|
seasonTemplateSports: many(seasonTemplateSports),
|
|
|
|
|
|
seasons: many(seasons),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
export const seasonTemplateSportsRelations = relations(seasonTemplateSports, ({ one }) => ({
|
|
|
|
|
|
template: one(seasonTemplates, {
|
|
|
|
|
|
fields: [seasonTemplateSports.templateId],
|
|
|
|
|
|
references: [seasonTemplates.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
sportsSeason: one(sportsSeasons, {
|
|
|
|
|
|
fields: [seasonTemplateSports.sportsSeasonId],
|
|
|
|
|
|
references: [sportsSeasons.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
export const seasonsRelations = relations(seasons, ({ one, many }) => ({
|
|
|
|
|
|
league: one(leagues, {
|
|
|
|
|
|
fields: [seasons.leagueId],
|
|
|
|
|
|
references: [leagues.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
template: one(seasonTemplates, {
|
|
|
|
|
|
fields: [seasons.templateId],
|
|
|
|
|
|
references: [seasonTemplates.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
teams: many(teams),
|
|
|
|
|
|
seasonSports: many(seasonSports),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
export const seasonSportsRelations = relations(seasonSports, ({ one }) => ({
|
|
|
|
|
|
season: one(seasons, {
|
|
|
|
|
|
fields: [seasonSports.seasonId],
|
|
|
|
|
|
references: [seasons.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
sportsSeason: one(sportsSeasons, {
|
|
|
|
|
|
fields: [seasonSports.sportsSeasonId],
|
|
|
|
|
|
references: [sportsSeasons.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
export const participantResultsRelations = relations(participantResults, ({ one }) => ({
|
|
|
|
|
|
participant: one(participants, {
|
|
|
|
|
|
fields: [participantResults.participantId],
|
|
|
|
|
|
references: [participants.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
sportsSeason: one(sportsSeasons, {
|
|
|
|
|
|
fields: [participantResults.sportsSeasonId],
|
|
|
|
|
|
references: [sportsSeasons.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
}));
|
2025-10-15 08:58:35 -07:00
|
|
|
|
|
|
|
|
|
|
export const teamsRelations = relations(teams, ({ one }) => ({
|
|
|
|
|
|
season: one(seasons, {
|
|
|
|
|
|
fields: [teams.seasonId],
|
|
|
|
|
|
references: [seasons.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
draftSlot: one(draftSlots, {
|
|
|
|
|
|
fields: [teams.id],
|
|
|
|
|
|
references: [draftSlots.teamId],
|
|
|
|
|
|
}),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
export const draftSlotsRelations = relations(draftSlots, ({ one }) => ({
|
|
|
|
|
|
season: one(seasons, {
|
|
|
|
|
|
fields: [draftSlots.seasonId],
|
|
|
|
|
|
references: [seasons.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
team: one(teams, {
|
|
|
|
|
|
fields: [draftSlots.teamId],
|
|
|
|
|
|
references: [teams.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
}));
|
2025-10-18 14:55:26 -07:00
|
|
|
|
|
2025-10-28 23:50:50 -07:00
|
|
|
|
export const draftPicksRelations = relations(draftPicks, ({ one }) => ({
|
|
|
|
|
|
season: one(seasons, {
|
|
|
|
|
|
fields: [draftPicks.seasonId],
|
|
|
|
|
|
references: [seasons.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
team: one(teams, {
|
|
|
|
|
|
fields: [draftPicks.teamId],
|
|
|
|
|
|
references: [teams.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
participant: one(participants, {
|
|
|
|
|
|
fields: [draftPicks.participantId],
|
|
|
|
|
|
references: [participants.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
2025-10-18 14:55:26 -07:00
|
|
|
|
export const draftQueueRelations = relations(draftQueue, ({ one }) => ({
|
|
|
|
|
|
season: one(seasons, {
|
|
|
|
|
|
fields: [draftQueue.seasonId],
|
|
|
|
|
|
references: [seasons.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
team: one(teams, {
|
|
|
|
|
|
fields: [draftQueue.teamId],
|
|
|
|
|
|
references: [teams.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
participant: one(participants, {
|
|
|
|
|
|
fields: [draftQueue.participantId],
|
|
|
|
|
|
references: [participants.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
}));
|
2025-10-21 23:22:17 -07:00
|
|
|
|
|
|
|
|
|
|
export const autodraftSettingsRelations = relations(autodraftSettings, ({ one }) => ({
|
|
|
|
|
|
season: one(seasons, {
|
|
|
|
|
|
fields: [autodraftSettings.seasonId],
|
|
|
|
|
|
references: [seasons.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
team: one(teams, {
|
|
|
|
|
|
fields: [autodraftSettings.teamId],
|
|
|
|
|
|
references: [teams.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
}));
|
2025-10-28 23:39:34 -07:00
|
|
|
|
|
|
|
|
|
|
// Scoring System Relations
|
|
|
|
|
|
|
|
|
|
|
|
export const scoringEventsRelations = relations(scoringEvents, ({ one, many }) => ({
|
|
|
|
|
|
sportsSeason: one(sportsSeasons, {
|
|
|
|
|
|
fields: [scoringEvents.sportsSeasonId],
|
|
|
|
|
|
references: [sportsSeasons.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
eventResults: many(eventResults),
|
|
|
|
|
|
playoffMatches: many(playoffMatches),
|
2026-02-14 22:30:12 -08:00
|
|
|
|
tournamentGroups: many(tournamentGroups),
|
Add CS2 Major Qualifying Points simulator and stage management (#260)
* Add CS2 Major qualifying points simulator
Implements a full CS2 Major tournament simulator with:
- 3-stage Swiss format (Opening Bo1, Elimination Bo1/Bo3, Decider all Bo3)
+ Champions Stage 8-team single-elimination (QF Bo3, SF Bo3, GF Bo5)
- Monte Carlo simulation (10,000 iterations) accumulating QP across 2 majors/season
- Sampled 24-team field per iteration: top 12 guaranteed, remaining weighted by 1/rank
- Stage 3 exits (placements 9-16) sub-ranked by W-L record (2-3 > 1-3 > 0-3)
- Stage assignments stored per-event so actual field composition drives simulation
- Admin CS Elo form for entering team Elo + HLTV world rankings
- Admin CS2 stage setup page for assigning teams to stages and tracking advancement
- Database migration: cs2_major_qualifying_points enum value + cs2_major_stage_results table
- 24 unit tests covering all exported pure functions
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Consolidate Elo + ranking input into generic elo-ratings page
The darts-elo and cs-elo pages were unreachable from the admin nav,
which always links to the generic elo-ratings page. Extended elo-ratings
to conditionally show world ranking fields for simulator types that need
it (darts_bracket, cs2_major_qualifying_points), then deleted the
redundant sport-specific pages.
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Consolidate server postgres connections into one shared pool
Four separate postgres() clients were open simultaneously (app, timer,
snapshots, socket), each defaulting to 10 connections, exhausting the
database's max_connections limit. Replaced with a single shared lazy-
initialized client in server/db.ts using a Proxy to defer the
DATABASE_URL check until first use (preserving test compatibility).
Also bumps the CS2 Champions Stage stochastic test from 200 → 1000
iterations to eliminate flakiness.
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Fix and() bug and add Swiss loop safety guard
- cs2-major-stage.ts: markCs2StageEliminations and setCs2FinalPlacements
were using JS && instead of Drizzle and(), causing WHERE to filter only
by participantId (not scoringEventId), which would update rows across
all events instead of just the target event
- cs-major-simulator.ts: add break guard in simulateSwiss while loop to
prevent infinite loop if pairGroups returns no pairs
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Fix all remaining code review issues
- cs2-major-stage.ts: use schema column reference for stageEliminated
in markCs2StageEliminations instead of raw SQL string
- cs-major-simulator.ts: simulateOneMajor now locks in known stage
results when a stage is complete (8 recorded eliminations), only
simulating the remaining stages during live events
- admin event page: add CS2 Stage Setup button for cs2_major_qualifying_points
simulator types; expose simulatorType in server loader type cast
- cs2-setup.tsx: replace document.getElementById DOM manipulation with
React state (eliminatedChecked map) for checkbox show/hide logic;
remove unused stageMap and unassignedParticipants variables
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Fix oxlint errors: non-null assertions, sort→toSorted, unused vars
- cs-major-simulator.ts: replace 5 non-null assertions (!) with safe
optional chaining / if-guards; replace 6 .sort() with .toSorted()
- cs2-major-stage.ts: remove unused `inArray` import
- cs2-setup.tsx: remove unused `assignedIds` variable
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Fix flaky Champions Stage stochastic test
The makeTeams(8) helper creates only a 70-pt Elo spread (1800→1730).
With the Champions Stage bracket math this gives team-0 a ~19.6% win
rate — right at the 0.2 threshold, causing the test to fail ~63% of
the time in CI despite 1000 iterations.
Use 100-pt steps (1800→1100) instead, giving team-0 a ~40% win rate
and raising the assertion threshold to 0.25 for a clear safety margin.
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-04-05 13:40:05 -07:00
|
|
|
|
cs2MajorStageResults: many(cs2MajorStageResults),
|
2025-10-28 23:39:34 -07:00
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
export const eventResultsRelations = relations(eventResults, ({ one }) => ({
|
|
|
|
|
|
scoringEvent: one(scoringEvents, {
|
|
|
|
|
|
fields: [eventResults.scoringEventId],
|
|
|
|
|
|
references: [scoringEvents.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
participant: one(participants, {
|
|
|
|
|
|
fields: [eventResults.participantId],
|
|
|
|
|
|
references: [participants.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
Add playoff match game scheduling and odds management (#135)
* Add playoff match games and odds storage
Introduces two new tables for bracket matchup detail storage:
- `playoff_match_games`: tracks individual game schedules within a
series matchup (game number, scheduledAt, status, per-game scores,
winner). Supports scheduled/complete/postponed status enum.
- `playoff_match_odds`: stores moneyline odds per participant per
matchup (single upsert record, no isLatest complexity).
Includes:
- Drizzle schema + relations with CASCADE deletes from playoff_matches
- Migration 0040_fat_puma.sql
- playoff-match-game.ts model with pure helpers: computeSeriesScore,
isSeriesComplete, getSeriesLeader — plus full CRUD
- playoff-match-odds.ts model with pure helpers: americanToImpliedProbability,
impliedProbabilityToAmerican, normalizeOdds — plus upsert/read/delete
- findPlayoffMatchesByEventId and findPlayoffMatchById updated to
include games and odds in their query results
- Bracket server route: add-game, update-game, delete-game,
upsert-odds, delete-odds actions
- Bracket admin UI: expandable per-match panel for game schedule
management and moneyline odds entry
- 41 new unit tests (18 game + 23 odds), all 810 tests passing
https://claude.ai/code/session_01Twt3D1bsEK3eXUhMaz6ee7
* Code review fixes: type safety, abstraction, and React correctness
- Derive PlayoffMatchGameStatus from schema enum instead of hardcoding
the string union, eliminating the duplicate source of truth
- updateGame now returns PlayoffMatchGame | undefined to reflect reality
when no row matches the ID
- Remove TOCTOU check-then-act in update-game action: call updateGame
directly and check the return value instead of a pre-flight findGameById
- Add status enum validation before the cast in update-game action
- Move impliedProbability computation inside upsertMatchOdds so callers
only provide moneylineOdds; the model owns the derivation
- Remove unnecessary dynamic import of americanToImpliedProbability in
the upsert-odds action (was already imported from the same module)
- Fix React list reconciliation bug: replace bare <> fragment with
<Fragment key={match.id}> so React can correctly track rows
https://claude.ai/code/session_01Twt3D1bsEK3eXUhMaz6ee7
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-11 14:17:43 -07:00
|
|
|
|
export const playoffMatchesRelations = relations(playoffMatches, ({ one, many }) => ({
|
2025-10-28 23:39:34 -07:00
|
|
|
|
scoringEvent: one(scoringEvents, {
|
|
|
|
|
|
fields: [playoffMatches.scoringEventId],
|
|
|
|
|
|
references: [scoringEvents.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
participant1: one(participants, {
|
|
|
|
|
|
fields: [playoffMatches.participant1Id],
|
|
|
|
|
|
references: [participants.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
participant2: one(participants, {
|
|
|
|
|
|
fields: [playoffMatches.participant2Id],
|
|
|
|
|
|
references: [participants.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
winner: one(participants, {
|
|
|
|
|
|
fields: [playoffMatches.winnerId],
|
|
|
|
|
|
references: [participants.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
loser: one(participants, {
|
|
|
|
|
|
fields: [playoffMatches.loserId],
|
|
|
|
|
|
references: [participants.id],
|
|
|
|
|
|
}),
|
Add playoff match game scheduling and odds management (#135)
* Add playoff match games and odds storage
Introduces two new tables for bracket matchup detail storage:
- `playoff_match_games`: tracks individual game schedules within a
series matchup (game number, scheduledAt, status, per-game scores,
winner). Supports scheduled/complete/postponed status enum.
- `playoff_match_odds`: stores moneyline odds per participant per
matchup (single upsert record, no isLatest complexity).
Includes:
- Drizzle schema + relations with CASCADE deletes from playoff_matches
- Migration 0040_fat_puma.sql
- playoff-match-game.ts model with pure helpers: computeSeriesScore,
isSeriesComplete, getSeriesLeader — plus full CRUD
- playoff-match-odds.ts model with pure helpers: americanToImpliedProbability,
impliedProbabilityToAmerican, normalizeOdds — plus upsert/read/delete
- findPlayoffMatchesByEventId and findPlayoffMatchById updated to
include games and odds in their query results
- Bracket server route: add-game, update-game, delete-game,
upsert-odds, delete-odds actions
- Bracket admin UI: expandable per-match panel for game schedule
management and moneyline odds entry
- 41 new unit tests (18 game + 23 odds), all 810 tests passing
https://claude.ai/code/session_01Twt3D1bsEK3eXUhMaz6ee7
* Code review fixes: type safety, abstraction, and React correctness
- Derive PlayoffMatchGameStatus from schema enum instead of hardcoding
the string union, eliminating the duplicate source of truth
- updateGame now returns PlayoffMatchGame | undefined to reflect reality
when no row matches the ID
- Remove TOCTOU check-then-act in update-game action: call updateGame
directly and check the return value instead of a pre-flight findGameById
- Add status enum validation before the cast in update-game action
- Move impliedProbability computation inside upsertMatchOdds so callers
only provide moneylineOdds; the model owns the derivation
- Remove unnecessary dynamic import of americanToImpliedProbability in
the upsert-odds action (was already imported from the same module)
- Fix React list reconciliation bug: replace bare <> fragment with
<Fragment key={match.id}> so React can correctly track rows
https://claude.ai/code/session_01Twt3D1bsEK3eXUhMaz6ee7
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-11 14:17:43 -07:00
|
|
|
|
games: many(playoffMatchGames),
|
|
|
|
|
|
odds: many(playoffMatchOdds),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
export const playoffMatchGamesRelations = relations(playoffMatchGames, ({ one }) => ({
|
|
|
|
|
|
match: one(playoffMatches, {
|
|
|
|
|
|
fields: [playoffMatchGames.playoffMatchId],
|
|
|
|
|
|
references: [playoffMatches.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
winner: one(participants, {
|
|
|
|
|
|
fields: [playoffMatchGames.winnerId],
|
|
|
|
|
|
references: [participants.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
export const playoffMatchOddsRelations = relations(playoffMatchOdds, ({ one }) => ({
|
|
|
|
|
|
match: one(playoffMatches, {
|
|
|
|
|
|
fields: [playoffMatchOdds.playoffMatchId],
|
|
|
|
|
|
references: [playoffMatches.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
participant: one(participants, {
|
|
|
|
|
|
fields: [playoffMatchOdds.participantId],
|
|
|
|
|
|
references: [participants.id],
|
|
|
|
|
|
}),
|
2025-10-28 23:39:34 -07:00
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
export const participantQualifyingTotalsRelations = relations(participantQualifyingTotals, ({ one }) => ({
|
|
|
|
|
|
participant: one(participants, {
|
|
|
|
|
|
fields: [participantQualifyingTotals.participantId],
|
|
|
|
|
|
references: [participants.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
sportsSeason: one(sportsSeasons, {
|
|
|
|
|
|
fields: [participantQualifyingTotals.sportsSeasonId],
|
|
|
|
|
|
references: [sportsSeasons.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
export const qualifyingPointConfigRelations = relations(qualifyingPointConfig, ({ one }) => ({
|
|
|
|
|
|
sportsSeason: one(sportsSeasons, {
|
|
|
|
|
|
fields: [qualifyingPointConfig.sportsSeasonId],
|
|
|
|
|
|
references: [sportsSeasons.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
export const teamSportScoresRelations = relations(teamSportScores, ({ one }) => ({
|
|
|
|
|
|
team: one(teams, {
|
|
|
|
|
|
fields: [teamSportScores.teamId],
|
|
|
|
|
|
references: [teams.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
sportsSeason: one(sportsSeasons, {
|
|
|
|
|
|
fields: [teamSportScores.sportsSeasonId],
|
|
|
|
|
|
references: [sportsSeasons.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
export const teamStandingsRelations = relations(teamStandings, ({ one }) => ({
|
|
|
|
|
|
team: one(teams, {
|
|
|
|
|
|
fields: [teamStandings.teamId],
|
|
|
|
|
|
references: [teams.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
season: one(seasons, {
|
|
|
|
|
|
fields: [teamStandings.seasonId],
|
|
|
|
|
|
references: [seasons.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
export const teamStandingsSnapshotsRelations = relations(teamStandingsSnapshots, ({ one }) => ({
|
|
|
|
|
|
team: one(teams, {
|
|
|
|
|
|
fields: [teamStandingsSnapshots.teamId],
|
|
|
|
|
|
references: [teams.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
season: one(seasons, {
|
|
|
|
|
|
fields: [teamStandingsSnapshots.seasonId],
|
|
|
|
|
|
references: [seasons.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
export const participantExpectedValuesRelations = relations(participantExpectedValues, ({ one }) => ({
|
|
|
|
|
|
participant: one(participants, {
|
|
|
|
|
|
fields: [participantExpectedValues.participantId],
|
|
|
|
|
|
references: [participants.id],
|
|
|
|
|
|
}),
|
2025-11-17 22:19:46 -08:00
|
|
|
|
sportsSeason: one(sportsSeasons, {
|
|
|
|
|
|
fields: [participantExpectedValues.sportsSeasonId],
|
|
|
|
|
|
references: [sportsSeasons.id],
|
2025-10-28 23:39:34 -07:00
|
|
|
|
}),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
export const participantSeasonResultsRelations = relations(participantSeasonResults, ({ one }) => ({
|
|
|
|
|
|
participant: one(participants, {
|
|
|
|
|
|
fields: [participantSeasonResults.participantId],
|
|
|
|
|
|
references: [participants.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
sportsSeason: one(sportsSeasons, {
|
|
|
|
|
|
fields: [participantSeasonResults.sportsSeasonId],
|
|
|
|
|
|
references: [sportsSeasons.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
}));
|
2026-02-14 22:30:12 -08:00
|
|
|
|
|
|
|
|
|
|
// Tournament Group Relations
|
|
|
|
|
|
export const tournamentGroupsRelations = relations(tournamentGroups, ({ one, many }) => ({
|
|
|
|
|
|
scoringEvent: one(scoringEvents, {
|
|
|
|
|
|
fields: [tournamentGroups.scoringEventId],
|
|
|
|
|
|
references: [scoringEvents.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
members: many(tournamentGroupMembers),
|
Add FIFA World Cup 2026 support with group stage display and Monte Carlo simulator (#242)
* Add FIFA World Cup 2026 support with group stage display and Monte Carlo simulator, fixes #127
- New `groupStageMatches` table for recording group play results (W/D/L, scores, matchday, schedule)
- `computeGroupStandings()` model function: pts → GD → GF → name tiebreaker ordering
- `GroupStageStandings` component showing all 12 groups with standings table and manager column
- Admin bracket UI: group match score entry, per-group standings, "Recalculate Floors" action
- `WorldCupSimulator`: 50k Monte Carlo covering group stage + best-8 3rd-place + knockout + 3rd place game
- Fuzzy name matching for national team Elo lookup (exact → substring → word-overlap), warns on miss
- Partial group completion: completed matches replayed with real scores, remaining matches simulated
- Elo priority: admin-entered sourceElo > futures odds converted to Elo > hardcoded national team ratings
- `fifa_48` bracket template: added Third Place Game round with `loserFeedsInto` on Semifinals
- Scoring rules: distinct 3rd/4th place for `fifa_48` (not averaged), QF losers share 5th–8th equally
- Floor scoring: SF participants guaranteed 4th (provisional), finalized after 3rd place game
- `recalculate-floors` admin action deletes and replays all results from scratch (fixes stale guard bug)
- Unique index on `(tournamentGroupId, participant1Id, participant2Id)` to prevent duplicate pairings
- Batch `findMatchesByGroupIds()` replacing N sequential queries in the sport season loader
- League home mini-standings now shows `actualPoints` (includes floor) instead of `totalPoints` only
- Elo ratings admin page supports World Cup (same bulk-import flow as snooker)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix TypeScript errors: update GroupStandingData type to use findMatchesByGroupIds
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Increase Node heap to 4GB for unit tests in CI to prevent OOM
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix OOM in CI: make WorldCupSimulator simulation count configurable for tests
Tests now pass numSimulations=500 instead of the production default of 50,000.
Six simulator tests × 50k iterations each was exhausting the 4GB heap on GitHub
Actions runners. Also reduce simGroupMatch stat tests from 50k to 5k iterations.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-29 10:27:47 -07:00
|
|
|
|
matches: many(groupStageMatches),
|
2026-02-14 22:30:12 -08:00
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
export const tournamentGroupMembersRelations = relations(tournamentGroupMembers, ({ one }) => ({
|
|
|
|
|
|
group: one(tournamentGroups, {
|
|
|
|
|
|
fields: [tournamentGroupMembers.tournamentGroupId],
|
|
|
|
|
|
references: [tournamentGroups.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
participant: one(participants, {
|
|
|
|
|
|
fields: [tournamentGroupMembers.participantId],
|
|
|
|
|
|
references: [participants.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
}));
|
2026-03-09 15:34:31 -07:00
|
|
|
|
|
Add FIFA World Cup 2026 support with group stage display and Monte Carlo simulator (#242)
* Add FIFA World Cup 2026 support with group stage display and Monte Carlo simulator, fixes #127
- New `groupStageMatches` table for recording group play results (W/D/L, scores, matchday, schedule)
- `computeGroupStandings()` model function: pts → GD → GF → name tiebreaker ordering
- `GroupStageStandings` component showing all 12 groups with standings table and manager column
- Admin bracket UI: group match score entry, per-group standings, "Recalculate Floors" action
- `WorldCupSimulator`: 50k Monte Carlo covering group stage + best-8 3rd-place + knockout + 3rd place game
- Fuzzy name matching for national team Elo lookup (exact → substring → word-overlap), warns on miss
- Partial group completion: completed matches replayed with real scores, remaining matches simulated
- Elo priority: admin-entered sourceElo > futures odds converted to Elo > hardcoded national team ratings
- `fifa_48` bracket template: added Third Place Game round with `loserFeedsInto` on Semifinals
- Scoring rules: distinct 3rd/4th place for `fifa_48` (not averaged), QF losers share 5th–8th equally
- Floor scoring: SF participants guaranteed 4th (provisional), finalized after 3rd place game
- `recalculate-floors` admin action deletes and replays all results from scratch (fixes stale guard bug)
- Unique index on `(tournamentGroupId, participant1Id, participant2Id)` to prevent duplicate pairings
- Batch `findMatchesByGroupIds()` replacing N sequential queries in the sport season loader
- League home mini-standings now shows `actualPoints` (includes floor) instead of `totalPoints` only
- Elo ratings admin page supports World Cup (same bulk-import flow as snooker)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix TypeScript errors: update GroupStandingData type to use findMatchesByGroupIds
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Increase Node heap to 4GB for unit tests in CI to prevent OOM
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix OOM in CI: make WorldCupSimulator simulation count configurable for tests
Tests now pass numSimulations=500 instead of the production default of 50,000.
Six simulator tests × 50k iterations each was exhausting the 4GB heap on GitHub
Actions runners. Also reduce simGroupMatch stat tests from 50k to 5k iterations.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-29 10:27:47 -07:00
|
|
|
|
export const groupStageMatchesRelations = relations(groupStageMatches, ({ one }) => ({
|
|
|
|
|
|
group: one(tournamentGroups, {
|
|
|
|
|
|
fields: [groupStageMatches.tournamentGroupId],
|
|
|
|
|
|
references: [tournamentGroups.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
participant1: one(participants, {
|
|
|
|
|
|
fields: [groupStageMatches.participant1Id],
|
|
|
|
|
|
references: [participants.id],
|
|
|
|
|
|
relationName: "groupMatchParticipant1",
|
|
|
|
|
|
}),
|
|
|
|
|
|
participant2: one(participants, {
|
|
|
|
|
|
fields: [groupStageMatches.participant2Id],
|
|
|
|
|
|
references: [participants.id],
|
|
|
|
|
|
relationName: "groupMatchParticipant2",
|
|
|
|
|
|
}),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
2026-03-09 15:34:31 -07:00
|
|
|
|
export const participantEvSnapshotsRelations = relations(participantEvSnapshots, ({ one }) => ({
|
|
|
|
|
|
participant: one(participants, {
|
|
|
|
|
|
fields: [participantEvSnapshots.participantId],
|
|
|
|
|
|
references: [participants.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
sportsSeason: one(sportsSeasons, {
|
|
|
|
|
|
fields: [participantEvSnapshots.sportsSeasonId],
|
|
|
|
|
|
references: [sportsSeasons.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
export const teamEvSnapshotsRelations = relations(teamEvSnapshots, ({ one }) => ({
|
|
|
|
|
|
team: one(teams, {
|
|
|
|
|
|
fields: [teamEvSnapshots.teamId],
|
|
|
|
|
|
references: [teams.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
season: one(seasons, {
|
|
|
|
|
|
fields: [teamEvSnapshots.seasonId],
|
|
|
|
|
|
references: [seasons.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
}));
|
2026-03-21 00:12:01 -07:00
|
|
|
|
|
|
|
|
|
|
// Regular season W/L standings for team-sport playoff_bracket seasons (NBA, NHL, etc.)
|
|
|
|
|
|
// Populated by the standings sync service; syncedAt = null means manually entered
|
|
|
|
|
|
export const regularSeasonStandings = pgTable("regular_season_standings", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
participantId: uuid("participant_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => participants.id, { onDelete: "cascade" }),
|
|
|
|
|
|
sportsSeasonId: uuid("sports_season_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => sportsSeasons.id, { onDelete: "cascade" }),
|
|
|
|
|
|
wins: integer("wins").notNull().default(0),
|
|
|
|
|
|
losses: integer("losses").notNull().default(0),
|
|
|
|
|
|
otLosses: integer("ot_losses"), // NHL overtime losses; null for NBA
|
|
|
|
|
|
ties: integer("ties"), // future sports (e.g. soccer)
|
|
|
|
|
|
winPct: decimal("win_pct", { precision: 5, scale: 4 }),
|
|
|
|
|
|
gamesPlayed: integer("games_played").notNull().default(0),
|
|
|
|
|
|
gamesBack: decimal("games_back", { precision: 5, scale: 1 }),
|
|
|
|
|
|
conference: varchar("conference", { length: 100 }),
|
|
|
|
|
|
division: varchar("division", { length: 100 }),
|
|
|
|
|
|
conferenceRank: integer("conference_rank"),
|
|
|
|
|
|
divisionRank: integer("division_rank"),
|
|
|
|
|
|
leagueRank: integer("league_rank"),
|
|
|
|
|
|
streak: varchar("streak", { length: 20 }), // e.g. "W3", "L2"
|
|
|
|
|
|
lastTen: varchar("last_ten", { length: 15 }), // e.g. "7-2-1"
|
|
|
|
|
|
homeRecord: varchar("home_record", { length: 15 }),
|
|
|
|
|
|
awayRecord: varchar("away_record", { length: 15 }),
|
|
|
|
|
|
externalTeamId: varchar("external_team_id", { length: 255 }),
|
2026-03-26 00:34:51 -07:00
|
|
|
|
srs: decimal("srs", { precision: 6, scale: 2 }), // Simple Rating System (point diff adjusted for SOS)
|
2026-03-21 00:12:01 -07:00
|
|
|
|
syncedAt: timestamp("synced_at"), // null = manually entered
|
|
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
}, (table) => ({
|
|
|
|
|
|
uniqueParticipantSeason: uniqueIndex("rss_participant_season_idx")
|
|
|
|
|
|
.on(table.participantId, table.sportsSeasonId),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
export const regularSeasonStandingsRelations = relations(regularSeasonStandings, ({ one }) => ({
|
|
|
|
|
|
participant: one(participants, {
|
|
|
|
|
|
fields: [regularSeasonStandings.participantId],
|
|
|
|
|
|
references: [participants.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
sportsSeason: one(sportsSeasons, {
|
|
|
|
|
|
fields: [regularSeasonStandings.sportsSeasonId],
|
|
|
|
|
|
references: [sportsSeasons.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
// Unmatched teams from a standings sync — awaiting admin resolution.
|
|
|
|
|
|
// Once the admin maps an external team to a participant, this record is deleted
|
|
|
|
|
|
// and the standing + participant.externalId are written.
|
|
|
|
|
|
export const pendingStandingsMappings = pgTable("pending_standings_mappings", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
sportsSeasonId: uuid("sports_season_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => sportsSeasons.id, { onDelete: "cascade" }),
|
|
|
|
|
|
externalTeamId: varchar("external_team_id", { length: 255 }).notNull(),
|
|
|
|
|
|
teamName: varchar("team_name", { length: 255 }).notNull(),
|
|
|
|
|
|
// Full standing data from the API, stored as JSON for use when resolving
|
|
|
|
|
|
standingData: jsonb("standing_data").notNull(),
|
|
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
}, (table) => ({
|
|
|
|
|
|
uniqueSeasonExternalId: uniqueIndex("psm_season_external_id_idx")
|
|
|
|
|
|
.on(table.sportsSeasonId, table.externalTeamId),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
export const pendingStandingsMappingsRelations = relations(pendingStandingsMappings, ({ one }) => ({
|
|
|
|
|
|
sportsSeason: one(sportsSeasons, {
|
|
|
|
|
|
fields: [pendingStandingsMappings.sportsSeasonId],
|
|
|
|
|
|
references: [sportsSeasons.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
}));
|
Add tennis Grand Slam simulator with surface Elo ratings, fixes #116 (#216)
Implements a Monte Carlo simulator for men's/women's tennis seasons scored
on the qualifying_points pattern. Simulates all 4 Grand Slam majors
(Australian Open, French Open, Wimbledon, US Open) using surface-specific
Elo ratings and ATP/WTA world rankings for seeding.
New table: participant_surface_elos — one row per (participant, season)
storing worldRanking, eloHard, eloClay, eloGrass.
Key design decisions:
- Seeding uses ATP/WTA world ranking (not Elo), matching real draw procedure
- Top 32 seeded with standard slot placement (1→0, 2→64, 3-4→quarters, etc.)
- QP per round with tie-splitting pre-applied: W=20, F=14, SF=9, QF=4, R16=1.5
- Completed majors read actual qualifyingPointsAwarded from eventResults
- 10,000 Monte Carlo simulations; column sums naturally 1.0 (no normalization)
Admin UI at /admin/sports-seasons/:id/surface-elo:
- 5-column grid (Player | Rank | Hard | Clay | Grass)
- Bulk import: "Name, ranking, hardElo, clayElo, grassElo" one per line
- Fuzzy name matching (bigram Dice coefficient) with "Did you mean?" suggestions
- Inline participant creation for unmatched names via useFetcher
- Saves Elos and auto-runs simulation on submit
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-23 23:59:35 -07:00
|
|
|
|
|
|
|
|
|
|
// ─── Participant Surface Elos ─────────────────────────────────────────────────
|
|
|
|
|
|
// Stores surface-specific Elo ratings for tennis (and future surface-based sports).
|
|
|
|
|
|
// One row per (participantId, sportsSeasonId); nullable per surface.
|
|
|
|
|
|
|
|
|
|
|
|
export const participantSurfaceElos = pgTable("participant_surface_elos", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
participantId: uuid("participant_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => participants.id, { onDelete: "cascade" }),
|
|
|
|
|
|
sportsSeasonId: uuid("sports_season_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => sportsSeasons.id, { onDelete: "cascade" }),
|
|
|
|
|
|
worldRanking: integer("world_ranking"),
|
|
|
|
|
|
eloHard: integer("elo_hard"),
|
|
|
|
|
|
eloClay: integer("elo_clay"),
|
|
|
|
|
|
eloGrass: integer("elo_grass"),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
}, (t) => ({
|
|
|
|
|
|
uniqueParticipantSeason: uniqueIndex("participant_surface_elos_unique")
|
|
|
|
|
|
.on(t.participantId, t.sportsSeasonId),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
export const participantSurfaceElosRelations = relations(participantSurfaceElos, ({ one }) => ({
|
|
|
|
|
|
participant: one(participants, {
|
|
|
|
|
|
fields: [participantSurfaceElos.participantId],
|
|
|
|
|
|
references: [participants.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
sportsSeason: one(sportsSeasons, {
|
|
|
|
|
|
fields: [participantSurfaceElos.sportsSeasonId],
|
|
|
|
|
|
references: [sportsSeasons.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
}));
|
Add golf qualifying points simulator (Plackett-Luce Monte Carlo) (#223)
* Add golf QP simulator with Plackett-Luce model, fixes #120
- New `participant_golf_skills` table (migration 0061) for SG: Total and
per-major American odds per player/season
- New `app/models/golf-skills.ts` with getGolfSkillsMap, getGolfSkillsForSeason,
batchUpsertGolfSkills
- Full `GolfSimulator` implementation replacing the TODO stub: Plackett-Luce
ranking model (PL_BETA=1.5, FIELD_SIZE=156), 10k Monte Carlo iterations,
awards QP by finishing position, ranks by total QP across all 4 majors
- New admin route `sports-seasons/:id/golf-skills` with bulk CSV import,
fuzzy name matching, per-player SG + per-major odds inputs; saves skills
and auto-runs simulation on submit
- Simulator dropdown on sport admin sorted alphabetically; renamed to
"Golf Qualifying Points Monte Carlo"
- Golf Skills button shown on sports season admin when simulator type is
golf_qualifying_points
- Extract normalizeName/diceCoefficient to shared `app/lib/fuzzy-match.ts`,
removing duplication from surface-elo and golf-skills routes
- Parallelize 4 DB queries in GolfSimulator.simulate() with Promise.all
- O(1) field array removal via swap-to-end + pop (was O(N) splice)
- Fix source tag: performance_model (not elo_simulation) for SG-based model
- 23 unit tests covering americanToImplied, getMajorOddsKey, resolveSkill,
simulateMajor, and Monte Carlo calibration properties
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix oxlint errors: no-non-null-assertion and eqeqeq
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-24 21:46:02 -07:00
|
|
|
|
|
|
|
|
|
|
// ─── Participant Golf Skills ───────────────────────────────────────────────────
|
|
|
|
|
|
// Stores golf-specific skill data for qualifying-points golf seasons.
|
|
|
|
|
|
// Primary metric: SG: Total (strokes gained per round vs. field average).
|
|
|
|
|
|
// Optional per-major American odds allow major-specific probability blending.
|
|
|
|
|
|
// One row per (participantId, sportsSeasonId).
|
|
|
|
|
|
|
|
|
|
|
|
export const participantGolfSkills = pgTable("participant_golf_skills", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
participantId: uuid("participant_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => participants.id, { onDelete: "cascade" }),
|
|
|
|
|
|
sportsSeasonId: uuid("sports_season_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => sportsSeasons.id, { onDelete: "cascade" }),
|
|
|
|
|
|
// Strokes gained total per round vs. field (e.g. +2.1 means 2.1 strokes/round better than avg)
|
|
|
|
|
|
sgTotal: decimal("sg_total", { precision: 5, scale: 2 }),
|
|
|
|
|
|
// DataGolf / OWGR rank for reference and admin ordering
|
|
|
|
|
|
datagolfRank: integer("datagolf_rank"),
|
|
|
|
|
|
// Per-major American odds (e.g. +400 = 20% implied win prob). All nullable.
|
|
|
|
|
|
mastersOdds: integer("masters_odds"),
|
|
|
|
|
|
usOpenOdds: integer("us_open_odds"),
|
|
|
|
|
|
openChampionshipOdds: integer("open_championship_odds"),
|
|
|
|
|
|
pgaChampionshipOdds: integer("pga_championship_odds"),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
}, (t) => ({
|
|
|
|
|
|
uniqueParticipantSeason: uniqueIndex("participant_golf_skills_unique")
|
|
|
|
|
|
.on(t.participantId, t.sportsSeasonId),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
export const participantGolfSkillsRelations = relations(participantGolfSkills, ({ one }) => ({
|
|
|
|
|
|
participant: one(participants, {
|
|
|
|
|
|
fields: [participantGolfSkills.participantId],
|
|
|
|
|
|
references: [participants.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
sportsSeason: one(sportsSeasons, {
|
|
|
|
|
|
fields: [participantGolfSkills.sportsSeasonId],
|
|
|
|
|
|
references: [sportsSeasons.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
}));
|
Add CS2 Major Qualifying Points simulator and stage management (#260)
* Add CS2 Major qualifying points simulator
Implements a full CS2 Major tournament simulator with:
- 3-stage Swiss format (Opening Bo1, Elimination Bo1/Bo3, Decider all Bo3)
+ Champions Stage 8-team single-elimination (QF Bo3, SF Bo3, GF Bo5)
- Monte Carlo simulation (10,000 iterations) accumulating QP across 2 majors/season
- Sampled 24-team field per iteration: top 12 guaranteed, remaining weighted by 1/rank
- Stage 3 exits (placements 9-16) sub-ranked by W-L record (2-3 > 1-3 > 0-3)
- Stage assignments stored per-event so actual field composition drives simulation
- Admin CS Elo form for entering team Elo + HLTV world rankings
- Admin CS2 stage setup page for assigning teams to stages and tracking advancement
- Database migration: cs2_major_qualifying_points enum value + cs2_major_stage_results table
- 24 unit tests covering all exported pure functions
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Consolidate Elo + ranking input into generic elo-ratings page
The darts-elo and cs-elo pages were unreachable from the admin nav,
which always links to the generic elo-ratings page. Extended elo-ratings
to conditionally show world ranking fields for simulator types that need
it (darts_bracket, cs2_major_qualifying_points), then deleted the
redundant sport-specific pages.
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Consolidate server postgres connections into one shared pool
Four separate postgres() clients were open simultaneously (app, timer,
snapshots, socket), each defaulting to 10 connections, exhausting the
database's max_connections limit. Replaced with a single shared lazy-
initialized client in server/db.ts using a Proxy to defer the
DATABASE_URL check until first use (preserving test compatibility).
Also bumps the CS2 Champions Stage stochastic test from 200 → 1000
iterations to eliminate flakiness.
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Fix and() bug and add Swiss loop safety guard
- cs2-major-stage.ts: markCs2StageEliminations and setCs2FinalPlacements
were using JS && instead of Drizzle and(), causing WHERE to filter only
by participantId (not scoringEventId), which would update rows across
all events instead of just the target event
- cs-major-simulator.ts: add break guard in simulateSwiss while loop to
prevent infinite loop if pairGroups returns no pairs
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Fix all remaining code review issues
- cs2-major-stage.ts: use schema column reference for stageEliminated
in markCs2StageEliminations instead of raw SQL string
- cs-major-simulator.ts: simulateOneMajor now locks in known stage
results when a stage is complete (8 recorded eliminations), only
simulating the remaining stages during live events
- admin event page: add CS2 Stage Setup button for cs2_major_qualifying_points
simulator types; expose simulatorType in server loader type cast
- cs2-setup.tsx: replace document.getElementById DOM manipulation with
React state (eliminatedChecked map) for checkbox show/hide logic;
remove unused stageMap and unassignedParticipants variables
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Fix oxlint errors: non-null assertions, sort→toSorted, unused vars
- cs-major-simulator.ts: replace 5 non-null assertions (!) with safe
optional chaining / if-guards; replace 6 .sort() with .toSorted()
- cs2-major-stage.ts: remove unused `inArray` import
- cs2-setup.tsx: remove unused `assignedIds` variable
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Fix flaky Champions Stage stochastic test
The makeTeams(8) helper creates only a 70-pt Elo spread (1800→1730).
With the Champions Stage bracket math this gives team-0 a ~19.6% win
rate — right at the 0.2 threshold, causing the test to fail ~63% of
the time in CI despite 1000 iterations.
Use 100-pt steps (1800→1100) instead, giving team-0 a ~40% win rate
and raising the assertion threshold to 0.25 for a clear safety margin.
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-04-05 13:40:05 -07:00
|
|
|
|
|
|
|
|
|
|
// ─── CS2 Major Stage Results ───────────────────────────────────────────────────
|
|
|
|
|
|
// Tracks which teams are assigned to each Swiss stage of a CS2 Major, and their
|
|
|
|
|
|
// advancement/elimination results. One row per (scoringEventId, participantId).
|
|
|
|
|
|
//
|
|
|
|
|
|
// stageEntry: 1=Opening Stage, 2=Elimination Stage, 3=Decider Stage
|
|
|
|
|
|
// stageEliminated: which stage they were eliminated at (null = made Champions Stage)
|
|
|
|
|
|
// stageEliminatedWins: wins at time of elimination (0, 1, or 2); used to rank teams
|
|
|
|
|
|
// within placements 9–16 for Stage 3 QP (2-3 > 1-3 > 0-3)
|
|
|
|
|
|
// finalPlacement: overall placement 1–32 (set after event completes)
|
|
|
|
|
|
|
|
|
|
|
|
export const cs2MajorStageResults = pgTable("cs2_major_stage_results", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
scoringEventId: uuid("scoring_event_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => scoringEvents.id, { onDelete: "cascade" }),
|
|
|
|
|
|
participantId: uuid("participant_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => participants.id, { onDelete: "cascade" }),
|
|
|
|
|
|
stageEntry: integer("stage_entry").notNull(),
|
|
|
|
|
|
stageEliminated: integer("stage_eliminated"),
|
|
|
|
|
|
stageEliminatedWins: integer("stage_eliminated_wins"),
|
|
|
|
|
|
finalPlacement: integer("final_placement"),
|
|
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
|
|
|
|
|
}, (t) => ({
|
|
|
|
|
|
uniqueEventParticipant: uniqueIndex("cs2_major_stage_results_unique")
|
|
|
|
|
|
.on(t.scoringEventId, t.participantId),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
export const cs2MajorStageResultsRelations = relations(cs2MajorStageResults, ({ one }) => ({
|
|
|
|
|
|
scoringEvent: one(scoringEvents, {
|
|
|
|
|
|
fields: [cs2MajorStageResults.scoringEventId],
|
|
|
|
|
|
references: [scoringEvents.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
participant: one(participants, {
|
|
|
|
|
|
fields: [cs2MajorStageResults.participantId],
|
|
|
|
|
|
references: [participants.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
}));
|
Add audit logging for commissioner actions (#293)
Closes #144
* feat: add commissioner audit log for league transparency (issue #144)
Adds a complete audit log system so league members can verify that
settings, draft order, picks, and time banks have not been quietly
changed without their awareness.
Changes:
- database/schema.ts: new `audit_action` enum + `commissioner_audit_log`
table (seasonId, leagueId, actorClerkId, actorDisplayName, action,
affectedTeamIds[], details jsonb, createdAt)
- drizzle/0075: generated migration for the new table
- app/models/audit-log.ts: createAuditLogEntry, getAuditLogForSeason
(paginated), logCommissionerAction (resolves display name automatically)
- app/lib/audit-log-display.ts: shared formatAuditDetail() helper used by
both the league home widget and the full audit log page
- app/routes/leagues/$leagueId.audit-log.tsx: new read-only route at
/leagues/:id/audit-log, accessible to all league members, with
action-type filter and pagination
- app/routes.ts: registers the new route
- League home page ($leagueId.server.ts / $leagueId.tsx): "Recent Activity"
summary card showing the last 5 entries with "View all" link
- Settings page ($leagueId.settings.tsx): "View Full Audit Log" link card;
audit log calls added for league/draft settings changes, draft order
set/randomized, and draft reset
- API routes: audit log calls added to draft.start, draft.pause,
draft.resume, draft.rollback, draft.adjust-time-bank, draft.force-autopick,
draft.force-manual-pick, draft.replace-pick
- Tests: 11 new unit tests for the audit-log model; mocks added to 3
existing route test files to account for the new logCommissionerAction call
https://claude.ai/code/session_01NdiwK2fbtKhAD3XuD58fTm
* fix: validate action filter URL param against known enum values
The action filter on the audit log route was cast directly from the URL
search param to AuditAction without validation. An invalid value would
be passed into the Drizzle inArray() call, potentially throwing a
PostgreSQL enum type error. Now validates against the actual enum values
before using the filter.
https://claude.ai/code/session_01NdiwK2fbtKhAD3XuD58fTm
* Fix lint errors: use !== instead of != and toSorted instead of sort
https://claude.ai/code/session_01NdiwK2fbtKhAD3XuD58fTm
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-04-13 18:45:39 -04:00
|
|
|
|
|
|
|
|
|
|
// ─── Commissioner Audit Log ────────────────────────────────────────────────────
|
|
|
|
|
|
// Immutable log of significant commissioner/admin actions per season.
|
|
|
|
|
|
// Readable by all league members for transparency; writable only by the
|
|
|
|
|
|
// server-side route actions that perform the underlying operations.
|
|
|
|
|
|
|
|
|
|
|
|
export const auditActionEnum = pgEnum("audit_action", [
|
|
|
|
|
|
"league_settings_changed",
|
|
|
|
|
|
"draft_settings_changed",
|
|
|
|
|
|
"scoring_rules_changed",
|
2026-04-14 21:41:05 -07:00
|
|
|
|
"sports_changed",
|
Add audit logging for commissioner actions (#293)
Closes #144
* feat: add commissioner audit log for league transparency (issue #144)
Adds a complete audit log system so league members can verify that
settings, draft order, picks, and time banks have not been quietly
changed without their awareness.
Changes:
- database/schema.ts: new `audit_action` enum + `commissioner_audit_log`
table (seasonId, leagueId, actorClerkId, actorDisplayName, action,
affectedTeamIds[], details jsonb, createdAt)
- drizzle/0075: generated migration for the new table
- app/models/audit-log.ts: createAuditLogEntry, getAuditLogForSeason
(paginated), logCommissionerAction (resolves display name automatically)
- app/lib/audit-log-display.ts: shared formatAuditDetail() helper used by
both the league home widget and the full audit log page
- app/routes/leagues/$leagueId.audit-log.tsx: new read-only route at
/leagues/:id/audit-log, accessible to all league members, with
action-type filter and pagination
- app/routes.ts: registers the new route
- League home page ($leagueId.server.ts / $leagueId.tsx): "Recent Activity"
summary card showing the last 5 entries with "View all" link
- Settings page ($leagueId.settings.tsx): "View Full Audit Log" link card;
audit log calls added for league/draft settings changes, draft order
set/randomized, and draft reset
- API routes: audit log calls added to draft.start, draft.pause,
draft.resume, draft.rollback, draft.adjust-time-bank, draft.force-autopick,
draft.force-manual-pick, draft.replace-pick
- Tests: 11 new unit tests for the audit-log model; mocks added to 3
existing route test files to account for the new logCommissionerAction call
https://claude.ai/code/session_01NdiwK2fbtKhAD3XuD58fTm
* fix: validate action filter URL param against known enum values
The action filter on the audit log route was cast directly from the URL
search param to AuditAction without validation. An invalid value would
be passed into the Drizzle inArray() call, potentially throwing a
PostgreSQL enum type error. Now validates against the actual enum values
before using the filter.
https://claude.ai/code/session_01NdiwK2fbtKhAD3XuD58fTm
* Fix lint errors: use !== instead of != and toSorted instead of sort
https://claude.ai/code/session_01NdiwK2fbtKhAD3XuD58fTm
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-04-13 18:45:39 -04:00
|
|
|
|
"draft_order_set",
|
|
|
|
|
|
"draft_order_randomized",
|
|
|
|
|
|
"draft_started",
|
|
|
|
|
|
"draft_paused",
|
|
|
|
|
|
"draft_resumed",
|
|
|
|
|
|
"draft_reset",
|
|
|
|
|
|
"draft_rollback",
|
|
|
|
|
|
"force_autopick",
|
|
|
|
|
|
"force_manual_pick",
|
|
|
|
|
|
"draft_pick_changed",
|
|
|
|
|
|
"time_bank_edited",
|
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
|
|
export const commissionerAuditLog = pgTable("commissioner_audit_log", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
seasonId: uuid("season_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => seasons.id, { onDelete: "cascade" }),
|
|
|
|
|
|
leagueId: uuid("league_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => leagues.id, { onDelete: "cascade" }),
|
2026-04-29 10:03:50 -07:00
|
|
|
|
actorUserId: varchar("actor_user_id", { length: 255 }).notNull(),
|
Add audit logging for commissioner actions (#293)
Closes #144
* feat: add commissioner audit log for league transparency (issue #144)
Adds a complete audit log system so league members can verify that
settings, draft order, picks, and time banks have not been quietly
changed without their awareness.
Changes:
- database/schema.ts: new `audit_action` enum + `commissioner_audit_log`
table (seasonId, leagueId, actorClerkId, actorDisplayName, action,
affectedTeamIds[], details jsonb, createdAt)
- drizzle/0075: generated migration for the new table
- app/models/audit-log.ts: createAuditLogEntry, getAuditLogForSeason
(paginated), logCommissionerAction (resolves display name automatically)
- app/lib/audit-log-display.ts: shared formatAuditDetail() helper used by
both the league home widget and the full audit log page
- app/routes/leagues/$leagueId.audit-log.tsx: new read-only route at
/leagues/:id/audit-log, accessible to all league members, with
action-type filter and pagination
- app/routes.ts: registers the new route
- League home page ($leagueId.server.ts / $leagueId.tsx): "Recent Activity"
summary card showing the last 5 entries with "View all" link
- Settings page ($leagueId.settings.tsx): "View Full Audit Log" link card;
audit log calls added for league/draft settings changes, draft order
set/randomized, and draft reset
- API routes: audit log calls added to draft.start, draft.pause,
draft.resume, draft.rollback, draft.adjust-time-bank, draft.force-autopick,
draft.force-manual-pick, draft.replace-pick
- Tests: 11 new unit tests for the audit-log model; mocks added to 3
existing route test files to account for the new logCommissionerAction call
https://claude.ai/code/session_01NdiwK2fbtKhAD3XuD58fTm
* fix: validate action filter URL param against known enum values
The action filter on the audit log route was cast directly from the URL
search param to AuditAction without validation. An invalid value would
be passed into the Drizzle inArray() call, potentially throwing a
PostgreSQL enum type error. Now validates against the actual enum values
before using the filter.
https://claude.ai/code/session_01NdiwK2fbtKhAD3XuD58fTm
* Fix lint errors: use !== instead of != and toSorted instead of sort
https://claude.ai/code/session_01NdiwK2fbtKhAD3XuD58fTm
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-04-13 18:45:39 -04:00
|
|
|
|
actorDisplayName: varchar("actor_display_name", { length: 255 }),
|
|
|
|
|
|
action: auditActionEnum("action").notNull(),
|
|
|
|
|
|
affectedTeamIds: text("affected_team_ids").array(),
|
|
|
|
|
|
details: jsonb("details"),
|
|
|
|
|
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
|
|
|
|
}, (t) => ({
|
|
|
|
|
|
auditLogSeasonIdx: index("audit_log_season_id_idx").on(t.seasonId, t.createdAt),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
export const commissionerAuditLogRelations = relations(commissionerAuditLog, ({ one }) => ({
|
|
|
|
|
|
season: one(seasons, {
|
|
|
|
|
|
fields: [commissionerAuditLog.seasonId],
|
|
|
|
|
|
references: [seasons.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
league: one(leagues, {
|
|
|
|
|
|
fields: [commissionerAuditLog.leagueId],
|
|
|
|
|
|
references: [leagues.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
}));
|
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
|
|
|
|
|
|
|
|
|
|
// ─── Team Score Events ─────────────────────────────────────────────────────────
|
|
|
|
|
|
// Records each time a team's total fantasy points increase as a result of a
|
|
|
|
|
|
// scoring event completing. Used for the "Recent Scores" feed on the standings
|
|
|
|
|
|
// page. One row per team per match (bracket sports) or per event (fallback).
|
|
|
|
|
|
// Participant IDs are stored at write time so attribution is accurate regardless
|
|
|
|
|
|
// of future match results.
|
|
|
|
|
|
|
|
|
|
|
|
export const teamScoreEvents = pgTable("team_score_events", {
|
|
|
|
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
|
|
|
|
teamId: uuid("team_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => teams.id, { onDelete: "cascade" }),
|
|
|
|
|
|
seasonId: uuid("season_id")
|
|
|
|
|
|
.notNull()
|
|
|
|
|
|
.references(() => seasons.id, { onDelete: "cascade" }),
|
|
|
|
|
|
scoringEventId: uuid("scoring_event_id")
|
|
|
|
|
|
.references(() => scoringEvents.id, { onDelete: "set null" }),
|
|
|
|
|
|
scoringEventName: varchar("scoring_event_name", { length: 255 }),
|
|
|
|
|
|
sportName: varchar("sport_name", { length: 255 }),
|
|
|
|
|
|
// Set for bracket sports (one row per match); NULL for event-level fallback rows.
|
|
|
|
|
|
matchId: uuid("match_id").references(() => playoffMatches.id, { onDelete: "set null" }),
|
|
|
|
|
|
// Participant IDs captured at write time — the specific drafted participants
|
|
|
|
|
|
// whose win/advancement caused this score change.
|
|
|
|
|
|
participantIds: text("participant_ids").array(),
|
|
|
|
|
|
pointsDelta: decimal("points_delta", { precision: 10, scale: 2 }).notNull(),
|
|
|
|
|
|
occurredAt: timestamp("occurred_at").defaultNow().notNull(),
|
|
|
|
|
|
}, (t) => ({
|
|
|
|
|
|
// Per-match rows: one row per (team, season, match)
|
|
|
|
|
|
uniqueTeamSeasonMatch: uniqueIndex("team_score_events_match_unique")
|
|
|
|
|
|
.on(t.teamId, t.seasonId, t.matchId)
|
|
|
|
|
|
.where(sql`match_id IS NOT NULL`),
|
|
|
|
|
|
// Event-level fallback rows: one row per (team, season, event) when no match data
|
|
|
|
|
|
uniqueTeamSeasonEvent: uniqueIndex("team_score_events_event_unique")
|
|
|
|
|
|
.on(t.teamId, t.seasonId, t.scoringEventId)
|
|
|
|
|
|
.where(sql`match_id IS NULL`),
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
export const teamScoreEventsRelations = relations(teamScoreEvents, ({ one }) => ({
|
|
|
|
|
|
team: one(teams, {
|
|
|
|
|
|
fields: [teamScoreEvents.teamId],
|
|
|
|
|
|
references: [teams.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
season: one(seasons, {
|
|
|
|
|
|
fields: [teamScoreEvents.seasonId],
|
|
|
|
|
|
references: [seasons.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
scoringEvent: one(scoringEvents, {
|
|
|
|
|
|
fields: [teamScoreEvents.scoringEventId],
|
|
|
|
|
|
references: [scoringEvents.id],
|
|
|
|
|
|
}),
|
|
|
|
|
|
}));
|