cutover + cleanup (2/2) (#367) * refactor(schema): rename per-window tables to season_* prefix Renames participants, participant_expected_values, participant_qualifying_totals, participant_results, participant_surface_elos to season_* prefixed names. Renames event_results.participant_id to season_participant_id. Phase 1a of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor: rename participant.ts model file to season-participant.ts Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(models): update model layer to use renamed schema exports Updated all model files to use the renamed schema exports from Task 1: - participants → seasonParticipants - participantExpectedValues → seasonParticipantExpectedValues - participantQualifyingTotals → seasonParticipantQualifyingTotals - participantResults → seasonParticipantResults - participantSurfaceElos → seasonParticipantSurfaceElos - eventResults.participantId → eventResults.seasonParticipantId - db.query relation accessors updated - Relation field .participant → .seasonParticipant where applicable - Import paths updated: ./participant → ./season-participant Files updated (14 model files + 3 test files): - draft-pick.ts - draft-utils.ts - event-result.ts - group-stage-match.ts - participant-result.ts - qualifying-points.ts - scoring-calculator.ts - scoring-event.ts - sports-season.ts - surface-elo.ts - team-score-events.ts - cs2-major-stage.ts - golf-skills.ts - participant-expected-value.ts - __tests__/sports-season.clone.test.ts - __tests__/auto-pick.test.ts - __tests__/executeAutoPick.timer.test.ts Typecheck errors decreased: 779 → 499 (280 fewer) All model file errors related to renamed schemas resolved. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(routes): update route layer to use renamed schema exports - Update model import from ~/models/participant to ~/models/season-participant - Rename schema.participants to schema.seasonParticipants - Rename schema.participantResults to schema.seasonParticipantResults - Rename db.query.participants to db.query.seasonParticipants - Update 9 route files and 1 test file Affected files: - admin.sports-seasons.$id.events.$eventId.bracket.server.ts - admin.sports-seasons.$id.participants.tsx - api/draft.force-manual-pick.ts - api/draft.make-pick.ts - api/draft.replace-pick.ts - api/seasons.$seasonId.draft.ts - leagues/$leagueId.draft-board.$seasonId.tsx - leagues/$leagueId.sports-seasons.$sportsSeasonId.server.ts - admin/__tests__/sports-seasons-participants.test.ts Error count reduced from 499 to 453 (46 errors fixed). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(routes): update route files for schema rename Update route imports from ~/models/participant to ~/models/season-participant and fix references to .participant/.participantId on event results to use .seasonParticipant/.seasonParticipantId after schema rename. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(services): update simulators and services for renamed schema Update all simulators, services, and server files to use renamed schema tables: - participants → seasonParticipants - participantExpectedValues → seasonParticipantExpectedValues - participantResults → seasonParticipantResults - eventResults.participantId → eventResults.seasonParticipantId Files updated: - 20 sport simulators (NBA, NHL, NFL, MLB, etc.) - probability-updater.ts - standings-sync/index.ts - sports-data-sync.server.ts - server/socket.ts Typecheck errors reduced from 365 to 0. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: rename per-window tables to season_* prefix * fix(tests): update mock query keys after participants table rename Change mock db.query.participants to db.query.seasonParticipants in test files to match the schema rename from commit66145a9. This fixes "Cannot read properties of undefined (reading 'findFirst'/'findMany')" errors that occurred when production code queries db.query.seasonParticipants but test mocks only defined the old participants key. Files updated: - app/services/simulations/__tests__/world-cup-simulator.test.ts - app/routes/api/__tests__/draft.force-manual-pick.test.ts - app/routes/api/__tests__/draft.force-manual-pick.timer-mode.test.ts - app/routes/api/__tests__/draft.make-pick.timer-mode.test.ts - server/__tests__/timer-autodraft.test.ts - app/models/__tests__/team-score-events.test.ts Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(tests): update remaining mock paths and keys after schema rename * fix(tests): final two mock stragglers after schema rename - draft-pick.test.ts: assertion on db.query.participantQualifyingTotals - process-match-result.test.ts: mock key participants → seasonParticipants Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * chore: add post-phase1a baseline capture (temp, for diff verification) * chore: capture pre-migration baselines * chore: remove post-phase1a capture helper after verification * schema: add canonical tournament & participant tables Adds tournaments, participants (canonical), tournament_results, and participant_surface_elos (canonical). Adds nullable tournament_id to scoring_events and nullable participant_id to season_participants. Phase 1b of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(models): add canonical tournament, participant, result, surface-elo models Adds CRUD modules for the canonical tables created in commit775b905. Each module mirrors existing app/models conventions (database() from ~/database/context, schema from ~/database/schema, mock-based tests). Key implementation notes: - participant.ts exports use "Canonical" prefix (CanonicalParticipant, createCanonicalParticipant, etc.) to avoid collision with existing season-participant.ts exports - All four models include comprehensive unit tests following the audit-log.test.ts pattern - Tests use mocked db responses (no real database access) - Upsert functions use onConflictDoUpdate for appropriate unique constraints Part of Phase 1b of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: create canonical tables, add nullable FKs * scripts: add extractTournamentIdentity helper for backfill Pure function that derives canonical (name, year) identity from a scoring_events row, stripping trailing 4-digit years from the name or falling back to eventDate. Used by the Phase 2 backfill to group per-window events into canonical tournaments. * scripts: add backfill orchestrator for canonical layer Populates canonical tournaments, participants, tournament_results, and participant_surface_elos from per-window data for qualifying-points sports. Skips already-linked rows, is idempotent, and supports dry-run mode. Critical invariants enforced by the implementation: - qualifying_points_awarded is never copied to tournament_results - season_participant_qualifying_totals is never touched - conflicting surface-Elo values between windows raise a loud error (recorded in report.errors) rather than overwriting * scripts: add backfill CLI with dry-run default Wires backfill-canonical-layer.ts to a CLI entry point exposed as `npm run backfill:canonical`. Defaults to --dry-run; requires --apply to actually write. Supports --sport=<uuid> to limit to a single sport. Exits 2 if the backfill reports errors (e.g., surface-Elo conflicts). * fix(backfill-cli): wrap runBackfill in DatabaseContext.run The orchestrator uses database() from ~/database/context, which requires AsyncLocalStorage to be populated. Wrap the CLI invocation with DatabaseContext.run(db, ...) using server/db's cached connection pool. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(backfill-cli): exit 0 on success so pg pool doesn't block The cached postgres connection pool keeps the Node event loop open after main() returns. Explicit process.exit(0) on success mirrors the pattern in scripts/capture-baseline.ts. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * schema: add check constraint requiring tournament_id for qualifying events Team sports (NHL, NBA, etc.) have scoring_events with no canonical tournament, so we can't require tournament_id globally. The constraint only applies when is_qualifying_event=true. Phase 3 Task 1 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(BatchResultEntry): make form intent configurable Canonical tournament admin page will submit with a different intent (batch-upsert-results). Existing per-window callers continue to get "batch-add-results" as the default, so no behavior changes. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(services): syncTournamentResults fan-out service * schema: add unique (scoring_event_id, season_participant_id) on event_results syncTournamentResults uses check-then-write on event_results. The unique index defends against race conditions (unlikely today — admin is single-writer — but safe to enforce). WARNING: if existing prod data has duplicate (scoring_event_id, season_participant_id) pairs, the migration will fail. Verify with: SELECT scoring_event_id, season_participant_id, count(*) FROM event_results GROUP BY 1, 2 HAVING count(*) > 1; Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): getSurfaceEloMap reads from canonical Switch the tennis simulator's Elo source from the per-window table to the canonical participant_surface_elos via season_participants.participant_id. Map key stays season_participant.id so the simulator's call pattern is unchanged. Other functions in this file still read/write the per-window table (seasonParticipantSurfaceElos). They back the old admin surface-elo page and are removed in Phase 4 after the canonical admin flow replaces them. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(admin): canonical tournament list + result entry routes New routes /admin/tournaments and /admin/tournaments/:id. The detail page lets admins enter tournament results once via paste-and-parse, then calls syncTournamentResults to fan out to every linked window. Phase 3 Task 4 of canonical tournament layer migration. * feat: per-window batch-add-results routes through canonical when linked If the scoring_event has a tournament_id, translate season_participant ids to canonical participant ids, upsert tournament_results, and fan out via syncTournamentResults. Team sports (no tournament link) keep the legacy direct-write path. Phase 3 Task 8 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): mirror batchUpsert writes to canonical table The simulator now reads surface Elo from the canonical table (participant_surface_elos). The existing per-window admin page still posts to batchUpsertSurfaceElos; without this change, those edits would silently fail to affect simulator output. Mirror every write to both tables until Phase 4 removes the per-window path entirely. Phase 3 Task 5 (partial — canonical write path; dedicated canonical admin UI deferred; existing page continues to work and now edits both tables). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat: auto-provision canonical tournaments and participants on create Creating new qualifying scoring_events or season_participants now auto-upserts the matching canonical rows. Needed so the check constraint doesn't reject qualifying events, and so new season participants flow through syncTournamentResults. - Extract tournament identity shared between backfill and event-creation into app/lib/tournament-identity.ts; scripts/backfill re-exports it. - createScoringEvent + bulkCreateScoringEvents now accept tournamentId. - Event creation routes auto-compute (name, year) and upsert tournament. - createParticipant + createManyParticipants auto-link to canonical participants by (sportId, name). Phase 3 Task 7 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(tests): update surface-elo tests for canonical mirror getSurfaceEloMap now joins through season_participants and returns rows keyed by seasonParticipantId (was participantId). batchUpsertSurfaceElos now performs a second db.select to resolve canonical links before mirroring writes; tests mock the lookup explicitly and exercise both the "no canonical link" short-circuit path and the "mirror to canonical" path. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: add check constraint + unique index for canonical * refactor(surface-elo): canonical-only; drop per-window path batchUpsertSurfaceElos now writes only to the canonical participant_surface_elos table (the mirror step is now the only step). getSurfaceElosForSeason joins through season_participants → canonical participants so the admin UI keeps its existing (id, participantId, sportsSeasonId, ...) row shape. season_participants without a canonical link get silently skipped. In practice every qualifying-points roster entry is canonical-linked after Phase 2 backfill + Phase 3 auto-linking on createParticipant. Phase 4 Tasks 2 + 3 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor: remove legacy direct-write fallback in batch-add-results Every qualifying scoring_event now has tournament_id (check constraint enforces it), so the non-canonical fallback is dead. Replace with an explicit error surface so any configuration regression becomes visible instead of silently bypassing canonical. Phase 4 Task 4. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * schema: drop season_participant_surface_elos table Table had no remaining readers after Phase 3 and no remaining writers after Phase 4 Task 2. Also removes the now-unrunnable Phase 2 backfill scripts and the backfill:canonical npm script — the backfill ran once and is preserved in git history (commits85bca8b,8186dbb,6f3438b,bc0f530,327c7b9). Phase 4 Task 5. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * docs(agents): describe canonical/per-window split Update database.md with the canonical/per-window model explanation, the syncTournamentResults fan-out contract, the check constraint, and the tennis-Men/Women quirk. Update domain-models.md to reflect the renamed per-window entities and the new canonical layer. Also update the drizzle-kit gotchas section with lessons from the migration: do not use --custom for renames; FK constraint naming can mismatch Drizzle convention. Phase 4 Task 6. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: drop season_participant_surface_elos * feat(admin): add Tournaments link to admin sidebar Missed in Phase 3 Task 4 — the /admin/tournaments route exists but was not reachable from the admin nav without typing the URL. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(lint): address 4 oxlint errors on canonical-layer-pr2 - Remove unused filterNewResults import (events batch-add-results legacy path was removed in Phase 4 Task 4). - Replace import() type annotation in sync-tournament-results test with a top-level type import (consistent-type-imports rule). - Hoist tableName helper out of makeFakeDb closure so it's not recreated per call (consistent-function-scoping rule). - eqeqeq: replace `!= null` with explicit null/undefined checks in tournament-identity. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> --------- Co-authored-by: Chris Parsons <chrisp@extrahop.com> Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
406 lines
14 KiB
TypeScript
406 lines
14 KiB
TypeScript
import { useState, useRef, useEffect } from "react";
|
|
import { useFetcher, useRevalidator } from "react-router";
|
|
import { Button } from "~/components/ui/button";
|
|
import { Textarea } from "~/components/ui/textarea";
|
|
import { Input } from "~/components/ui/input";
|
|
import { Badge } from "~/components/ui/badge";
|
|
import {
|
|
Select,
|
|
SelectContent,
|
|
SelectItem,
|
|
SelectTrigger,
|
|
SelectValue,
|
|
} from "~/components/ui/select";
|
|
import {
|
|
Table,
|
|
TableBody,
|
|
TableCell,
|
|
TableHead,
|
|
TableHeader,
|
|
TableRow,
|
|
} from "~/components/ui/table";
|
|
import {
|
|
Card,
|
|
CardContent,
|
|
CardDescription,
|
|
CardHeader,
|
|
CardTitle,
|
|
} from "~/components/ui/card";
|
|
import { CheckCircle2, Trophy } from "lucide-react";
|
|
import { parseResultsText } from "~/lib/parse-results-text";
|
|
|
|
interface Participant {
|
|
id: string;
|
|
name: string;
|
|
}
|
|
|
|
interface ResolvedRow {
|
|
placement: number;
|
|
rawName: string;
|
|
participantId: string | null; // null = unresolved
|
|
}
|
|
|
|
type Stage = "idle" | "preview" | "saving";
|
|
|
|
interface BatchResultEntryProps {
|
|
participants: Participant[];
|
|
sportsSeasonId: string;
|
|
existingResultParticipantIds: Set<string>;
|
|
/**
|
|
* Form intent name posted on "Save All". Defaults to "batch-add-results" for
|
|
* the existing per-window flow. Canonical tournament pages override this.
|
|
*/
|
|
intent?: string;
|
|
}
|
|
|
|
export function BatchResultEntry({
|
|
participants,
|
|
sportsSeasonId,
|
|
existingResultParticipantIds,
|
|
intent = "batch-add-results",
|
|
}: BatchResultEntryProps) {
|
|
const [stage, setStage] = useState<Stage>("idle");
|
|
const [pasteText, setPasteText] = useState("");
|
|
const [rows, setRows] = useState<ResolvedRow[]>([]);
|
|
const [parseError, setParseError] = useState<string | null>(null);
|
|
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
|
const [addingNewFor, setAddingNewFor] = useState<number | null>(null);
|
|
const [newParticipantName, setNewParticipantName] = useState("");
|
|
const { revalidate } = useRevalidator();
|
|
|
|
const saveFetcher = useFetcher();
|
|
const createParticipantFetcher = useFetcher();
|
|
|
|
// Mutable lookup built from the prop — updated when new participants are created
|
|
const participantByNameRef = useRef(
|
|
new Map(participants.map((p) => [p.name.toLowerCase(), p]))
|
|
);
|
|
// Mutable list — grows when new participants are created inline
|
|
const participantsRef = useRef([...participants]);
|
|
|
|
const pendingNewParticipantRowRef = useRef<number | null>(null);
|
|
|
|
const createData = createParticipantFetcher.data as
|
|
| { newParticipant?: { id: string; name: string }; error?: string }
|
|
| undefined;
|
|
|
|
const saveData = saveFetcher.data as
|
|
| { success?: string; error?: string }
|
|
| undefined;
|
|
|
|
// When createParticipantFetcher returns a new participant, auto-select it
|
|
useEffect(() => {
|
|
if (
|
|
createData?.newParticipant &&
|
|
pendingNewParticipantRowRef.current !== null
|
|
) {
|
|
const newP = createData.newParticipant;
|
|
const rowIndex = pendingNewParticipantRowRef.current;
|
|
pendingNewParticipantRowRef.current = null;
|
|
// Update lookup and list
|
|
participantByNameRef.current.set(newP.name.toLowerCase(), newP);
|
|
participantsRef.current.push(newP);
|
|
// Auto-select for the row
|
|
setRows((prev) =>
|
|
prev.map((row, i) =>
|
|
i === rowIndex ? { ...row, participantId: newP.id } : row
|
|
)
|
|
);
|
|
}
|
|
}, [createData]);
|
|
|
|
// Watch save fetcher for completion
|
|
useEffect(() => {
|
|
if (stage === "saving" && saveFetcher.state === "idle" && saveData) {
|
|
if (saveData.success) {
|
|
setSuccessMessage(saveData.success);
|
|
setStage("idle");
|
|
setPasteText("");
|
|
setRows([]);
|
|
revalidate();
|
|
} else if (saveData.error) {
|
|
setStage("preview");
|
|
}
|
|
}
|
|
}, [saveFetcher.state, saveData, stage, revalidate]);
|
|
|
|
function handleParse() {
|
|
setParseError(null);
|
|
const parsed = parseResultsText(pasteText);
|
|
if (parsed.length === 0) {
|
|
setParseError("No results found. Check the format and try again.");
|
|
return;
|
|
}
|
|
|
|
const resolved: ResolvedRow[] = parsed.map((line) => {
|
|
const match = participantByNameRef.current.get(line.rawName.toLowerCase());
|
|
return {
|
|
placement: line.placement,
|
|
rawName: line.rawName,
|
|
participantId: match ? match.id : null,
|
|
};
|
|
});
|
|
|
|
setRows(resolved);
|
|
setStage("preview");
|
|
}
|
|
|
|
function setRowParticipant(index: number, participantId: string) {
|
|
setRows((prev) =>
|
|
prev.map((row, i) => (i === index ? { ...row, participantId } : row))
|
|
);
|
|
}
|
|
|
|
function handleAddNewParticipant(index: number) {
|
|
setAddingNewFor(index);
|
|
setNewParticipantName(rows[index].rawName);
|
|
}
|
|
|
|
function handleCreateParticipant(index: number) {
|
|
if (!newParticipantName.trim()) return;
|
|
const formData = new FormData();
|
|
formData.set("intent", "create-participant");
|
|
formData.set("name", newParticipantName.trim());
|
|
formData.set("sportsSeasonId", sportsSeasonId);
|
|
createParticipantFetcher.submit(formData, { method: "post" });
|
|
pendingNewParticipantRowRef.current = index;
|
|
setAddingNewFor(null);
|
|
setNewParticipantName("");
|
|
}
|
|
|
|
function handleConfirm() {
|
|
if (!allResolved || rows.length === 0) return;
|
|
setStage("saving");
|
|
const results = rows
|
|
.filter((r) => r.participantId !== null)
|
|
.map((r) => ({
|
|
participantId: r.participantId as string,
|
|
placement: r.placement,
|
|
}));
|
|
const formData = new FormData();
|
|
formData.set("intent", intent);
|
|
formData.set("results", JSON.stringify(results));
|
|
saveFetcher.submit(formData, { method: "post" });
|
|
}
|
|
|
|
const allResolved = rows.every((r) => r.participantId !== null);
|
|
|
|
if (successMessage) {
|
|
return (
|
|
<Card className="border-emerald-500/30">
|
|
<CardContent className="pt-6">
|
|
<div className="flex items-center gap-2 text-emerald-500">
|
|
<CheckCircle2 className="h-4 w-4" />
|
|
<span className="text-sm font-medium">{successMessage}</span>
|
|
<Button
|
|
variant="ghost"
|
|
size="sm"
|
|
className="ml-auto"
|
|
onClick={() => setSuccessMessage(null)}
|
|
>
|
|
Import more
|
|
</Button>
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
);
|
|
}
|
|
|
|
// Participants available for mapping — exclude those already in saved results
|
|
// (but include any that are currently resolved in this batch, to allow re-use)
|
|
const resolvedIds = new Set(rows.map((r) => r.participantId).filter(Boolean) as string[]);
|
|
const availableParticipants = participantsRef.current.filter(
|
|
(p) => !existingResultParticipantIds.has(p.id) || resolvedIds.has(p.id)
|
|
);
|
|
|
|
return (
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle>
|
|
<Trophy className="inline mr-2 h-4 w-4" />
|
|
Batch Paste Results
|
|
</CardTitle>
|
|
<CardDescription>
|
|
Paste a ranked results list to import all placements at once. Format:{" "}
|
|
<code className="text-xs bg-muted px-1 py-0.5 rounded">
|
|
1. Player Name
|
|
</code>{" "}
|
|
— use{" "}
|
|
<code className="text-xs bg-muted px-1 py-0.5 rounded">T3</code> or
|
|
repeat a rank for ties.
|
|
</CardDescription>
|
|
</CardHeader>
|
|
<CardContent>
|
|
{stage === "idle" && (
|
|
<div className="space-y-4">
|
|
<Textarea
|
|
value={pasteText}
|
|
onChange={(e) => setPasteText(e.target.value)}
|
|
placeholder={
|
|
"1. Gerwyn Price\n2. Luke Littler\nT3. Michael van Gerwen\nT3. Peter Wright\n5. Damon Heta"
|
|
}
|
|
rows={10}
|
|
className="font-mono text-sm"
|
|
/>
|
|
{parseError && (
|
|
<p className="text-sm text-destructive">{parseError}</p>
|
|
)}
|
|
<Button
|
|
onClick={handleParse}
|
|
disabled={!pasteText.trim()}
|
|
className="w-full"
|
|
>
|
|
Parse Results
|
|
</Button>
|
|
</div>
|
|
)}
|
|
|
|
{(stage === "preview" || stage === "saving") && (
|
|
<div className="space-y-4">
|
|
<Table>
|
|
<TableHeader>
|
|
<TableRow>
|
|
<TableHead className="w-24">Placement</TableHead>
|
|
<TableHead>Parsed Name</TableHead>
|
|
<TableHead>Matched Participant</TableHead>
|
|
<TableHead className="w-20">Status</TableHead>
|
|
</TableRow>
|
|
</TableHeader>
|
|
<TableBody>
|
|
{rows.map((row, index) => {
|
|
const isTied =
|
|
rows.filter((r) => r.placement === row.placement).length >
|
|
1;
|
|
|
|
return (
|
|
<TableRow key={`${row.placement}-${row.rawName}`}>
|
|
<TableCell>
|
|
<div className="flex items-center gap-1">
|
|
<span className="font-semibold">{row.placement}</span>
|
|
{isTied && (
|
|
<Badge
|
|
variant="outline"
|
|
className="text-xs px-1 py-0"
|
|
>
|
|
T
|
|
</Badge>
|
|
)}
|
|
</div>
|
|
</TableCell>
|
|
<TableCell className="text-muted-foreground text-sm">
|
|
{row.rawName}
|
|
</TableCell>
|
|
<TableCell>
|
|
{row.participantId ? (
|
|
<span className="text-sm text-emerald-600 dark:text-emerald-400 font-medium">
|
|
{participantsRef.current.find(
|
|
(p) => p.id === row.participantId
|
|
)?.name ?? row.rawName}
|
|
</span>
|
|
) : addingNewFor === index ? (
|
|
<div className="flex items-center gap-2">
|
|
<Input
|
|
value={newParticipantName}
|
|
onChange={(e) =>
|
|
setNewParticipantName(e.target.value)
|
|
}
|
|
className="h-8 text-sm"
|
|
placeholder="Participant name"
|
|
/>
|
|
<Button
|
|
size="sm"
|
|
className="h-8"
|
|
onClick={() => handleCreateParticipant(index)}
|
|
disabled={!newParticipantName.trim() || createParticipantFetcher.state !== "idle"}
|
|
>
|
|
Add
|
|
</Button>
|
|
<Button
|
|
size="sm"
|
|
variant="ghost"
|
|
className="h-8"
|
|
onClick={() => setAddingNewFor(null)}
|
|
>
|
|
Cancel
|
|
</Button>
|
|
</div>
|
|
) : (
|
|
<Select
|
|
onValueChange={(val) => {
|
|
if (val === "__add_new__") {
|
|
handleAddNewParticipant(index);
|
|
} else {
|
|
setRowParticipant(index, val);
|
|
}
|
|
}}
|
|
>
|
|
<SelectTrigger className="h-8 text-sm">
|
|
<SelectValue placeholder="Select participant…" />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
{availableParticipants.map((p) => (
|
|
<SelectItem key={p.id} value={p.id}>
|
|
{p.name}
|
|
</SelectItem>
|
|
))}
|
|
<SelectItem value="__add_new__">
|
|
+ Add new participant…
|
|
</SelectItem>
|
|
</SelectContent>
|
|
</Select>
|
|
)}
|
|
</TableCell>
|
|
<TableCell>
|
|
{row.participantId ? (
|
|
<Badge className="bg-emerald-500 text-white text-xs">
|
|
✓
|
|
</Badge>
|
|
) : (
|
|
<Badge variant="destructive" className="text-xs">
|
|
!
|
|
</Badge>
|
|
)}
|
|
</TableCell>
|
|
</TableRow>
|
|
);
|
|
})}
|
|
</TableBody>
|
|
</Table>
|
|
|
|
{saveData?.error && (
|
|
<p className="text-sm text-destructive">{saveData.error}</p>
|
|
)}
|
|
{createData?.error && (
|
|
<p className="text-sm text-destructive">{createData.error}</p>
|
|
)}
|
|
|
|
<div className="flex gap-2">
|
|
<Button
|
|
variant="outline"
|
|
onClick={() => setStage("idle")}
|
|
disabled={stage === "saving"}
|
|
>
|
|
Back
|
|
</Button>
|
|
<Button
|
|
onClick={handleConfirm}
|
|
disabled={!allResolved || stage === "saving"}
|
|
className="flex-1"
|
|
>
|
|
{stage === "saving" ? (
|
|
"Saving…"
|
|
) : (
|
|
<>
|
|
<CheckCircle2 className="mr-2 h-4 w-4" />
|
|
Confirm & Save All ({rows.length} result
|
|
{rows.length === 1 ? "" : "s"})
|
|
</>
|
|
)}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</CardContent>
|
|
</Card>
|
|
);
|
|
}
|