diff --git a/app/_actions/deck/__tests__/bulk-edit.test.ts b/app/_actions/deck/__tests__/bulk-edit.test.ts index 477f873..cc6328b 100644 --- a/app/_actions/deck/__tests__/bulk-edit.test.ts +++ b/app/_actions/deck/__tests__/bulk-edit.test.ts @@ -280,32 +280,24 @@ describe("bulkReplaceDeck", () => { expect(result.removed).toBe(0); }); - it("returns unmatched card names without generating an add op", async () => { + it("keeps the deck intact when a bulk edit contains an unresolved name", async () => { asOwner(); - // Forest resolves; "Not A Real Card" does not (no exact, no fuzzy prefix). mockCardFindMany .mockResolvedValueOnce([{ id: 1, name: "Forest" }] as never) - // Fuzzy lookup for the unmatched name - .mockResolvedValueOnce([] as never); - mockDeckCardFindMany.mockResolvedValue([] as never); + .mockResolvedValueOnce([{ id: 2, name: "Sol Ring" }] as never); + mockDeckCardFindMany.mockResolvedValue([ + { id: "dc-1", cardId: 1, zone: Zone.MAINBOARD, quantity: 1, categoryLinks: [] }, + { id: "dc-2", cardId: 2, zone: Zone.MAINBOARD, quantity: 1, categoryLinks: [] }, + ] as never); - const result = await bulkReplaceDeck( - DECK_ID, - "1 Forest\n1 Not A Real Card Xyz", - ); + const result = await bulkReplaceDeck(DECK_ID, "4 Forest\n1 Sol Rign"); - expect(result.unmatchedNames).toEqual(["Not A Real Card Xyz"]); - const [, , changes] = mockApply.mock.calls[0]!; - // Only the Forest add — no add for the unmatched name. - expect(changes).toEqual([ - { - op: "add", - cardId: 1, - quantity: 1, - zone: Zone.MAINBOARD, - categories: [], - }, - ]); - expect(result.added).toBe(1); + expect(mockApply).not.toHaveBeenCalled(); + expect(result).toMatchObject({ + added: 0, + removed: 0, + updated: 0, + unmatchedNames: ["Sol Rign"], + }); }); }); diff --git a/app/_components/builder/bulk-edit-dialog.tsx b/app/_components/builder/bulk-edit-dialog.tsx index 0e44017..7127c3a 100644 --- a/app/_components/builder/bulk-edit-dialog.tsx +++ b/app/_components/builder/bulk-edit-dialog.tsx @@ -49,6 +49,7 @@ export function BulkEditDialog({ const [result, setResult] = useState(null); const [error, setError] = useState(null); const [isPending, startTransition] = useTransition(); + const hasUnmatchedNames = (result?.unmatchedNames.length ?? 0) > 0; const summary = useMemo(() => { const parsed = parseDecklist(text, detectFormat(text)); @@ -140,15 +141,16 @@ export function BulkEditDialog({ )} {result && ( - - {result.unmatchedNames.length === 0 && result.warnings.length === 0 ? ( + + {!hasUnmatchedNames && result.warnings.length === 0 ? ( ) : ( )} - Saved — added {result.added}, removed {result.removed}, updated{" "} - {result.updated} + {hasUnmatchedNames + ? "Fix unmatched card names before saving" + : `Saved. Added ${result.added}, removed ${result.removed}, updated ${result.updated}.`}
@@ -159,18 +161,12 @@ export function BulkEditDialog({ ))} )} - {result.unmatchedNames.length > 0 && ( -
-

- {result.unmatchedNames.length} unmatched card - {result.unmatchedNames.length !== 1 ? "s" : ""} skipped: -

-
    - {result.unmatchedNames.map((name) => ( -
  • {name}
  • - ))} -
-
+ {hasUnmatchedNames && ( +
    + {result.unmatchedNames.map((name) => ( +
  • {name}
  • + ))} +
)}
diff --git a/lib/deck/io/__tests__/card-resolver.test.ts b/lib/deck/io/__tests__/card-resolver.test.ts index 3f8bbb4..c65492c 100644 --- a/lib/deck/io/__tests__/card-resolver.test.ts +++ b/lib/deck/io/__tests__/card-resolver.test.ts @@ -81,7 +81,46 @@ describe("resolveCardNames", () => { expect(row!.warnings).toHaveLength(0); }); - it("picks the closest-length candidate", async () => { + it("rejects a same-prefix, similar-length but different card (false positive)", async () => { + mockFindMany + .mockResolvedValueOnce([] as never) + .mockResolvedValueOnce([{ id: 42, name: "Lightning Helix" }] as never); + + const [row] = await resolveCardNames([parsed("Lightning Bolt")]); + + expect(row).toMatchObject({ cardId: null, match: { kind: "none" } }); + expect(row!.warnings).toHaveLength(0); + }); + + it("still fuzzy-matches a real typo", async () => { + mockFindMany + .mockResolvedValueOnce([] as never) + .mockResolvedValueOnce([ + { id: 1, name: "Lightning Helix" }, + { id: 2, name: "Lightning Bolt" }, + ] as never); + + const [row] = await resolveCardNames([parsed("Lightnign Bolt")]); + + expect(row).toMatchObject({ cardId: 2, matchedName: "Lightning Bolt" }); + expect(row!.match.kind).toBe("fuzzy"); + expect(row!.warnings).toHaveLength(1); + }); + + it("returns none when two candidates tie", async () => { + mockFindMany + .mockResolvedValueOnce([] as never) + .mockResolvedValueOnce([ + { id: 1, name: "Shockwave" }, + { id: 2, name: "Shockwaze" }, + ] as never); + + const [row] = await resolveCardNames([parsed("Shockwaxe")]); + + expect(row).toMatchObject({ cardId: null, match: { kind: "none" } }); + }); + + it("picks the closest candidate", async () => { mockFindMany .mockResolvedValueOnce([] as never) .mockResolvedValueOnce([ diff --git a/lib/deck/io/card-resolver.ts b/lib/deck/io/card-resolver.ts index bd008e3..13138ce 100644 --- a/lib/deck/io/card-resolver.ts +++ b/lib/deck/io/card-resolver.ts @@ -20,34 +20,52 @@ type CardResolution = { }; const FUZZY_PREFIX_LEN = 4; -const FUZZY_TAKE = 20; -const FUZZY_MIN_CONFIDENCE = 0.7; +const FUZZY_TAKE = 100; +const FUZZY_MIN_CONFIDENCE = 0.85; -/** Pick the candidate whose name length is closest to the target name. */ +function editDistance(a: string, b: string): number { + let prev = Array.from({ length: b.length + 1 }, (_, j) => j); + for (let i = 1; i <= a.length; i++) { + const curr = [i]; + for (let j = 1; j <= b.length; j++) { + curr[j] = Math.min( + prev[j]! + 1, + curr[j - 1]! + 1, + prev[j - 1]! + (a[i - 1] === b[j - 1] ? 0 : 1), + ); + } + prev = curr; + } + return prev[b.length]!; +} + +/** + * Pick the prefix candidate with the lowest edit distance to the target. + * Returns undefined when no candidate shares the prefix or the top two tie + * (ambiguous, so substituting either would be a guess). + */ function pickClosest( target: string, candidates: ReadonlyArray<{ id: number; name: string }>, ): { id: number; name: string } | undefined { - return [...candidates] + const ranked = candidates .filter((c) => c.name.toLowerCase().startsWith(target.slice(0, FUZZY_PREFIX_LEN)), ) - .sort( - (a, b) => - Math.abs(a.name.length - target.length) - - Math.abs(b.name.length - target.length), - )[0]; + .map((c) => ({ c, d: editDistance(c.name.toLowerCase(), target) })) + .sort((x, y) => x.d - y.d); + if (ranked.length > 1 && ranked[0]!.d === ranked[1]!.d) return undefined; + return ranked[0]?.c; } function fuzzyConfidence(matchedName: string, target: string): number { - const lenDelta = Math.abs(matchedName.length - target.length); - const raw = 1 - lenDelta / Math.max(target.length, 1); - return Math.max(0, Math.min(1, raw)); + const dist = editDistance(matchedName.toLowerCase(), target); + return Math.max(0, 1 - dist / Math.max(matchedName.length, target.length, 1)); } /** * Resolve parsed card names to canonical Card rows. Tries exact (case-insensitive) - * first, then a length-delta fuzzy match per unmatched name. + * first, then a edit-distance fuzzy match per unmatched name. */ export async function resolveCardNames( parsed: readonly ParsedCard[], diff --git a/lib/deck/io/intake.ts b/lib/deck/io/intake.ts index c3a405f..bd9ba83 100644 --- a/lib/deck/io/intake.ts +++ b/lib/deck/io/intake.ts @@ -159,8 +159,10 @@ export async function intakeDecklist(input: IntakeInput): Promise // that yielded nothing would delete every card. A parse failure produces // zero parsed cards *with* warnings — distinct from a legitimately empty // paste (zero cards, no warnings), which may intentionally clear the deck. - // Abort with a warning-only result rather than silently wiping the deck. - if (mode === "replace" && parsed.cards.length === 0 && warnings.length > 0) { + if ( + mode === "replace" && + (unmatchedNames.length > 0 || (parsed.cards.length === 0 && warnings.length > 0)) + ) { return { applied: 0, added: 0, removed: 0, updated: 0, unmatchedNames, warnings }; }